如何将行写入 NamedTemporaryFile 然后打印每一行

how do I write lines to a NamedTemporaryFile then print each line

我正在尝试解压缩包含 csv 文件的 zip 文件,并将 csv 文件中的所有行写入 NamedTemporaryFile。然后打印临时文件中的行以确保它已正确写入所需的行。这是我当前的代码,当“打印(行)”被调用时 returns 空白。

with zipfile.ZipFile(file_name) as zip_fp:
        for item in zip_fp.namelist():
            temp_file = NamedTemporaryFile()
            with zip_fp.open(item) as fp:
                with open(temp_file.name, mode='wb+') as temp_fp:
                    temp_fp.writelines(fp.readlines())
                    for line in temp_fp:
                        print(line)

请帮忙。

那是因为 temp_fp.writelines(fp.readlines()) 已将所有行写入文件,并且光标现在位于文件末尾,因此您不会得到任何东西。试试下面的代码(最后 3 行已添加到您的代码中):

with zipfile.ZipFile(file_name) as zip_fp:
        for item in zip_fp.namelist():
            temp_file = NamedTemporaryFile()
            with zip_fp.open(item) as fp:
                with open(temp_file.name, mode='wb+') as temp_fp:
                    temp_fp.writelines(fp.readlines())
                with open(temp_file.name, mode='r') as temp_fp:
                    for line in temp_fp:
                        print (line)
                

OR - seek 到文件开头并读取所有行:

with zipfile.ZipFile(file_name) as zip_fp:
        for item in zip_fp.namelist():
            temp_file = NamedTemporaryFile()
            with zip_fp.open(item) as fp:
                with open(temp_file.name, mode='wb+') as temp_fp:
                    temp_fp.writelines(fp.readlines())
                    # SEEK TO START OF FILE
                    temp_fp.seek(0,0)
                    for line in temp_fp:
                        print (line)
                

原因是写入查找到文件末尾,所以没有什么可读的了。此代码:

with zip_fp.open(item) as fp:
     with open(temp_file.name, mode='wb+') as temp_fp:
         temp_fp.writelines(fp.readlines())
             for line in temp_fp:
                 print(line)

执行以下操作:

  • 以 fp 格式打开 zip:
  • 打开临时文件 temp_fp
  • 从 temp_fp 的开头写入(因为我们不处于追加模式)。
  • 读取文件末尾后的任何内容(即什么都不读)。

没有理由检查写入是否有效:它会的。然而,如果你想这样做,像这样的东西会起作用:

with zip_fp.open(item) as fp, temp_file.open("wb+") as tmpf:
    for line in fp:
        tmpf.writelines([line])
with tmp_file.open("rb") as tmpf:
    for line in tmpf:
        print(line)

注意这里的一些修正——一直使用路径对象,一行中有多个 with,并通过直接写入来避免 ram 浪费。

顺便说一句,这些应该是二进制模式吗?