ValueError:Python中已关闭文件的readline

时间:2015-01-27 14:59:55

标签: python csv

这是我的代码:

import csv

with open('test.csv', 'rb') as csvfile:
    x = csv.reader(csvfile,delimiter=',',quotechar='|')

for row in x:
    print (row)

我收到以下错误:

ValueError: readline of closed file

可能是什么问题?

2 个答案:

答案 0 :(得分:6)

您的缩进无序

import csv

with open('test.csv', 'rb') as csvfile:
    x = csv.reader(csvfile,delimiter=',',quotechar='|')

    for row in x:
        print (row)

是正确的缩进

with open('test.csv', 'rb') as csvfile:创建一个文件对象,但在块结束后调用该文件的__close__方法。与在Python中一样,非缩进关闭块,当您编写for row in x:时,您已退出块。因此x现已关闭,您无法对此执行任何操作。

答案 1 :(得分:1)

您的代码没有正确缩进。将rb替换为r

import csv

with open('test.csv','r') as csvfile:
    x = csv.reader(csvfile,delimiter=',',quotechar='|')

    for row in x:
        print (row)