我正在对下载的文件进行一些文件处理。我在with
块内调用一个函数,它正在进行一些文件处理,并将结果写入临时文件。但是从函数返回后,我的文件被关闭了,我得到了ValueError: seek of closed file
。
有人可以向我解释为什么临时文件仍在with
块内时关闭吗?
def run(ftp_file):
with tempfile.TemporaryFile() as src, tempfile.TemporaryFile() as dest:
for line in ftp_file.readlines():
# some file cleansing here
src.write(line)
src.seek(0)
process_file1(src, dest)
assert src.closed is True
assert dest.closed is True
dest.seek(0) # raises ValueError: seek of closed file
def process_file1(src, dest):
""" Write some columns """
fieldnames = ['f1', 'f2']
reader = csv.DictReader(io.TextIOWrapper(src))
writer = csv.DictWriter(io.TextIOWrapper(dest, write_through=True), fieldnames=fieldnames)
writer.writeheader()
for row in reader:
writer.writerow({col: row[col] for col in fieldnames})
答案 0 :(得分:3)
问题是io.TextIOWrapper
:
with tempfile.TemporaryFile() as fobj:
print(fobj.closed)
io.TextIOWrapper(fobj)
print(fobj.closed)
输出:
False
True
变化:
with tempfile.TemporaryFile() as src, tempfile.TemporaryFile() as dest:
为:
with io.TextIOWrapper(tempfile.TemporaryFile()) as src, \
io.TextIOWrapper(tempfile.TemporaryFile()) as dest:
因此,您只需分别为scr
和dest
创建一个文件对象。