Python-从临时fi中编写和读取

2024-04-28 09:47:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

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


Tags: 文件数据对象代码versionwithlinetmp
3条回答

根据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)

您遇到了范围问题;文件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

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

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

因此,一个安全的解决方案是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.

相关问题 更多 >