在python函数中读取CSV文件的最简单方法

时间:2019-07-01 17:32:48

标签: python-3.x csv

我试图运行此脚本以读取同一目录中的.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')

1 个答案:

答案 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')