Python:使用块关闭文件

时间:2018-02-09 13:15:10

标签: python

我正在对下载的文件进行一些文件处理。我在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})

1 个答案:

答案 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:

因此,您只需分别为scrdest创建一个文件对象。