我试图运行此脚本以读取同一目录中的.csv文件,但执行时出现以下错误:
Traceback (most recent call last):
File "C:\Users\Isaac\Desktop\TEST\csvreader.py", line 11, in <module>
csvReader('test.csv')
File "C:\Users\Isaac\Desktop\TEST\csvreader.py", line 7, in csvReader
for row in reader:
ValueError: I/O operation on closed file.
>>>
import csv
#Function for reading .csv file
def csvReader(filename):
with open(filename) as file:
reader = csv.reader(file, delimiter =' ')
for row in reader:
print(row[0])
#Function that reads file
csvReader('test.csv')
答案 0 :(得分:2)
您正在尝试从reader
块后面的with
对象读取数据,此时文件将被关闭。使用with
块打开的文件将在退出with
块时关闭。将您的阅读器代码放入with
块中,如下所示。
import csv
#Function for reading .csv file
def csvReader(filename):
with open(filename) as file:
reader = csv.reader(file, delimiter =' ')
for row in reader:
print(row[0])
#Function that reads file
csvReader('test.csv')