2016-05-15 215 views
-2

我使用的Spyder的Python 2.7在Windows 8.我试图打开和读取一个CSV文件和查看存储在它的所有数据,但是这是我得到什么,而不是:如何在Python中读取CSV文件?

runfile('C:/Users/John/Documents/Python Scripts/FLInsuraneFile.py', wdir='C:/Users/John/Documents/Python Scripts') 
<_io.TextIOWrapper name='FL_insurance_sample.csv' mode='r' encoding='cp1252'> 

如何我可以正确打开文件吗?

+0

你想读取或写入文件吗?你想使用[**'csv' **](https://docs.python.org/2/library/csv.html)模块,还是只打印整个内容? –

+0

@Dan发布与您的问题相关的代码? – aBiologist

回答

0

第一件事,你必须明白一个CSV文件的内部运作。 CSV文件是由行和列组成,例如:

| NAME | AGE | ROOM | 
| ---------------------| 
| Kaleb | 15 | 256 | 
| ---------------------| 
| John | 15 | 257 | 
| ---------------------| 
| Anna | 16 | 269 | 

当垂直元件列,且水平元件是行。行包含许多类型的数据,如名称/年龄/房间。列仅包含一种类型的数据,如名称。

继续前进,这里是读取CSV的示例函数。 请仔细研究代码。

def read_csv(csv_file): 
    data = [] 
    with open(csv_file, 'r') as f: 

     # create a list of rows in the CSV file 
     rows = f.readlines() 

     # strip white-space and newlines 
     rows = list(map(lambda x:x.strip(), rows)) 

     for row in rows: 

      # further split each row into columns assuming delimiter is comma 
      row = row.split(',') 

      # append to data-frame our new row-object with columns 
      data.append(row) 

    return data 

现在为什么要这样做?那么,这个功能允许你按行/列访问你的CSV文件。这意味着索引更容易。使用上述功能请看下面的例子:

csvFile = 'test.csv' 

# invoke our function 
data = read_csv(csvFile) 

# get row 1, column 2 of file 
print(data[1][2]) 

# get entirety of row 2 
print(data[2]) 

# get row 0, columns 1 & 2 
print(data[0][1], data[0][2]) 

正如你所看到的,我们可以很容易地通过使用我们的read_csv()功能和创建嵌套列表对象访问文件的不同部分。最后,如果要打印到整个文件,则只需在创建数据对象后使用for循环即可。

data = read_csv(csvFile) 

for row in data: 
    print(row) 

总之,大熊猫是非常适合大数据的科学,但如果你只是 想读/访问CSV,这个功能就好了。不需要为小任务安装大包,除非你想要:)。

祝你好运!