gpt4 book ai didi

python - CSV Reader 对象获取 ValueError : I/O operation on closed file?

转载 作者:行者123 更新时间:2023-11-30 23:04:28 25 4
gpt4 key购买 nike

我正在创建一个 csv.reader 对象,并将其设置为实例变量,但是当我尝试迭代它时,出现错误,提示我正在尝试在封闭的对象上进行操作文件。 reader 是否仍然以某种方式链接到该文件?我将其分配在我的 with open(blah) block 中,所以我很困惑为什么会发生这种情况。

这是我的代码:

    def __init__(self, infile, header_file, transact_file):
self.infile = infile
self.header_of = header_file
self.transact_of = transact_file

def create_reader(self):
"""Create a csv reader."""

with open(self.infile, 'r') as inf:
logging.info('Infile name: {0}'.format(inf))
self.csv_reader = reader(inf, quotechar='"')

def parse_headers(self):
"""Separate header files ("H", "S") from transaction files."""

headers = []
transactions = []

for row in self.csv_reader:
row_type = row[0]
logging.info('Row type is: {0}'.format(row_type))
if row_type == 'H':
logging.info('Row added to header list.')
headers.append(row)
elif row_type == 'S':
if row not in headers:
logging.info('Row added to header list.')
headers.append(row)
else:
logging.info('Row added to transaction list.')
transactions.append(row)

# Debugging and verification
logging.info('Header list contains: {0}'.format('\n'.join([str(header) for header
in headers])))
logging.info('Transaction list contains: {0}'.format(
'\n'.join([str(trans) for trans in transactions])))

这是我的错误堆栈:

Traceback (most recent call last):                                                                                    x
File "./gen_pre.py", line 155, in <module> x
main() x
File "./gen_pre.py", line 25, in main x
parser.run_process() x
File "./gen_pre.py", line 140, in run_process x
self.parse_headers() x
File "./gen_pre.py", line 68, in parse_headers x
for row in self.csv_reader: x
ValueError: I/O operation on closed file

最佳答案

当您离开区 block 时,

with 会自动关闭文件。

你必须做

self.inf = open(self.infile, 'r')

self.csv_reader = reader(self.inf, quotechar='"') # self.inf

您必须手动关闭该文件。

def close_reader(self):
self.csv_reader.close()
self.inf.close()

关于python - CSV Reader 对象获取 ValueError : I/O operation on closed file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com