[英]How to read a csv file in Python?
I need to read a csv
file (named CityPop.csv
) and this is the code I have: 我需要读取一个
csv
文件(名为CityPop.csv
),这是我的代码:
import csv
with open ('CityPop.csv', 'r') as f:
read_data = f.read()
for line in f:
record=line.strip().split(",")
print read_data
f.close()
But when I try to run it, nothing is output. 但是当我尝试运行它时,什么也没有输出。
I am not sure how to continue; 我不确定如何继续; this only leads into more advanced tasks I need to complete, which is difficult if I can't even figure this out.
这只会导致我需要完成更高级的任务,如果我什至不知道这是很难的。
Try this code 试试这个代码
import csv
with open ('CityPop.csv', 'r') as f:
reader = csv.reader(f, delimiter=",")
#read_data = f.read()
for line in reader:
print(line)
#record=line.strip().split(",")
#print (read_data)
f.close()
EDIT As Ralf said " f.close()
is not necessary when using a with block" 编辑正如拉尔夫所说:“在使用with块时不需要
f.close()
”
An easier way of reading csv files using pandas library - 使用Pandas库读取CSV文件的更简单方法-
import pandas
df = pandas.read_csv('CityPop.csv')
print(df)
or you can try modifying your code as below - 或者您可以尝试如下修改代码-
import csv
with open ('CityPop.csv', 'r') as f:
read_data = csv.reader(f,delimiter=',')
for row in read_data:
print(row)
I suggest you follow the example from the docs of the python csv
module : 我建议您遵循python
csv
模块文档中的示例:
import csv
with open('CityPop.csv') as f:
csv_reader = csv.reader(f, delimiter=', ')
for row in csv_reader:
print ', '.join(row)
Analizing your code, there are a few issues: 分析您的代码,有一些问题:
f.close()
if you use a with
statement, the file will be closed automatically when exiting the with
block with
语句,则无需调用f.close()
,退出with
块时文件将自动关闭 with
block, as the variable read_data
is defined inside it with
块中,因为变量read_data
是在其中定义的 read_data
( for line in read_data:
), because you already used f.read()
so that iterating over f
will no yield anything read_data
( for line in read_data:
),因为您已经使用过f.read()
因此对f
迭代将不会产生任何结果 record
each time, so I don't know why you want to it that way record
,所以我不知道您为什么要这样做 import csv
with open('CityPro.cvs') as f:
r = csv.reader(f, delimiter=',')
for line in r:
print(line)
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.