【问题标题】:Python - writing and reading from a temporary filePython - 从临时文件中写入和读取
【发布时间】:2017-02-20 09:17:06
【问题描述】:

我正在尝试创建一个临时文件,我在另一个文件的某些行中写入该文件,然后从数据中创建一些对象。我不知道如何找到并打开临时文件以便阅读。我的代码:

with tempfile.TemporaryFile() as tmp:
    lines = open(file1).readlines()
    tmp.writelines(lines[2:-1])

dependencyList = []

for line in tmp:
    groupId = textwrap.dedent(line.split(':')[0])
    artifactId = line.split(':')[1]
    version = line.split(':')[3]
    scope = str.strip(line.split(':')[4])
    dependencyObject = depenObj(groupId, artifactId, version, scope)
    dependencyList.append(dependencyObject)
tmp.close()

基本上我只是想制作一个中间人临时文档,以防止意外覆盖文件。

【问题讨论】:

  • 我从来没有使用过临时文件,你有什么理由不使用标准的 open() writeread 方法吗?
  • 我想防止文件名已经存在并且我可以覆盖它的可能性
  • 1.您是否考虑过简单地将一个脚本的输出通过管道传输到第二个脚本的输入? 2. 您是否正在检查以确保临时文件存在于您正在查找的路径中?
  • 您的范围有问题。临时文件tmp 仅存在于创建它的with 循环范围内。
  • 请发表您的评论作为答案,Pierce Darragh,我可以修改它。

标签: python temporary-files


【解决方案1】:

根据docs,当TemporaryFile 关闭时文件被删除,当您退出with 子句时会发生这种情况。所以...不要退出with 子句。倒带文件并在with 中完成您的工作。

with tempfile.TemporaryFile() as tmp:
    lines = open(file1).readlines()
    tmp.writelines(lines[2:-1])
    tmp.seek(0)

    for line in tmp:
        groupId = textwrap.dedent(line.split(':')[0])
        artifactId = line.split(':')[1]
        version = line.split(':')[3]
        scope = str.strip(line.split(':')[4])
        dependencyObject = depenObj(groupId, artifactId, version, scope)
        dependencyList.append(dependencyObject)

【讨论】:

  • 谢谢你解决了它。 .seek(0) 完成了什么?
  • 你说的是倒带吗?
  • 在您tmp.writelines 之后,文件指针位于文件末尾。 tmp.seek(0) 再次回到开头(倒带——也许这是古老的盒式磁带术语!)所以你可以阅读你写的东西。
【解决方案2】:

您遇到了范围问题;文件tmp 仅存在于创建它的with 语句的范围内。此外,如果您想稍后在初始with 之外访问该文件,则需要使用NamedTemporaryFile(这使操作系统能够访问该文件)。另外,我不确定您为什么要尝试附加到临时文件...因为在您实例化它之前它并不存在。

试试这个:

import tempfile

tmp = tempfile.NamedTemporaryFile()

# Open the file for writing.
with open(tmp.name, 'w') as f:
    f.write(stuff) # where `stuff` is, y'know... stuff to write (a string)

...

# Open the file for reading.
with open(tmp.name) as f:
    for line in f:
        ... # more things here

【讨论】:

  • 如果您要读取文件而不关闭并重新打开它,请确保在写入文件后添加“f.seek(0)”。否则你会读到文件的结尾,这会给你错误的结果。
  • 我在尝试打开临时文件时收到Permission denied
  • @CGFoX 这表明您的文件系统存在问题,我认为。您的操作系统有一个临时文件的默认位置,这就是 Python 用于这些文件的位置。例如,在 macOS 10.14 Mojave(我相信还有其他版本)上,位置是 /var/folders/。如果您收到有关权限被拒绝的错误消息,则您可能没有对此位置的写入权限。
  • tempfile.NamedTemporaryFile() 有一个默认的delete=True,因此可以在with 范围之外或关闭时访问。
【解决方案3】:

如果文件需要第二次打开,例如由另一个进程读取这个might cause trouble on Windows OS

在命名的临时文件仍处于打开状态时,该名称是否可用于第二次打开文件,因平台而异(在 Unix 上可以这样使用;在 Windows NT 或更高版本上不能)。

因此,一个安全的解决方案是改为create a temporary directory,然后在其中手动创建一个文件:

import os.path
import tempfile

with tempfile.TemporaryDirectory() as td:
    f_name = os.path.join(td, 'test')
    with open(f_name, 'w') as fh:
        fh.write('<content>')
    # Now the file is written and closed and can be used for reading.

【讨论】:

  • from pathlib import Path 然后f_name = Path(td) / 'test'
猜你喜欢
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 2020-06-24
  • 1970-01-01
相关资源
最近更新 更多