我正在创建一个csv.reader
对象,将其设置为实例变量,但是当我尝试迭代它时,我得到一个错误,说我正在尝试对已关闭的文件进行操作。 reader
仍然以某种方式链接到文件吗?我在我的with open(blah)
块中分配它,所以我很困惑为什么会发生这种情况。
这是我的代码:
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
答案 0 :(得分:2)
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()
答案 1 :(得分:1)
上下文管理器很棒,因为它们会自动为您关闭文件。您可以读取整个文件并将行列表传递给CSV阅读器,而不是手动打开和关闭文件:
def create_reader(self):
"""Create a csv reader."""
with open(self.infile, 'r') as inf:
logging.info('Infile name: {0}'.format(inf))
file_data = inf.readlines()
self.csv_reader = reader(file_data, quotechar='"')
csv.reader
对象将接受它可以迭代的任何内容,因此文件中每一行的列表(来自readlines
)都可以正常工作。