python版本:Python 3.6.1
python开发工具:JetBrains PyCharm 2018.3.6 x64
csv测试数据.csv→文件下载地址
https://url71.ctfile.com/f/13238771-529977809-0e9b4d
(访问密码:8835)
import csv
import sys
filename = 'csv测试数据.csv'
data = []
try:
with open(filename, encoding='utf8') as f:
reader = csv.reader(f)
header = next(reader)
data = [row for row in reader]
except csv.Error as e:
print("Error reading CSV file at line %s: %s" % (reader.line_num, e))
sys.exit(-1)
if header:
print(header)
print('=================')
for datarow in data:
print(datarow)
在文件reader = csv.reader(f)后提示IO操作要在文件关闭前执行,使用with方法打开了文件,生成的文件操作实例在with语句之外是无效的,因为with语句之外文件已经关闭了。
import csv
import sys
filename = 'csv测试数据.csv'
data = []
try:
with open(filename, encoding='utf8') as f:
reader = csv.reader(f)
header = next(reader) # 进行缩进,在with方法里面
data = [row for row in reader] # 进行缩进,在with方法里面
except csv.Error as e:
print("Error reading CSV file at line %s: %s" % (reader.line_num, e))
sys.exit(-1)
if header:
print(header)
print('=================')
for datarow in data:
print(datarow)
在文件操作中,提示ValueError: I/O operation on closed file. 大多是由于代码缩进问题导致,检查一下代码缩进就可以解决了