ValueError:Python中已关闭文件的readline

SZA*_*SZA 5 python csv

这是我的代码:

import csv

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

for row in x:
    print (row)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

ValueError: readline of closed file
Run Code Online (Sandbox Code Playgroud)

可能是什么问题?

Bha*_*Rao 7

你的缩进不正常

import csv

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

    for row in x:
        print (row)
Run Code Online (Sandbox Code Playgroud)

是正确的缩进

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