Python-从临时文件写入和读取

Python-从临时文件写入和读取,python,temporary-files,Python,Temporary Files,我试图创建一个临时文件,从另一个文件中写入一些行,然后从数据中生成一些对象。我不知道如何找到和打开临时文件,以便我可以阅读它。我的代码: with tempfile.TemporaryFile() as tmp: lines = open(file1).readlines() tmp.writelines(lines[2:-1]) dependencyList = [] for line in tmp: groupId = textwrap.dedent(line.s

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

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()
本质上,我只是想制作一个中间人临时文档,以防止意外覆盖文件

根据,当
临时文件
关闭时,文件将被删除,当您退出
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
语句的范围内。此外,如果要在以后使用
访问初始文件之外的文件,则需要使用名为的临时文件(这使操作系统能够访问该文件)。另外,我不知道你为什么试图附加到一个临时文件。。。因为在你实例化它之前它是不存在的

试试这个:

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

如果需要第二次打开文件,例如,通过不同的进程读取文件,请执行以下操作:

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

因此,一个安全的解决方案是,取而代之,然后在其中手动创建一个文件:

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.
导入操作系统路径
导入临时文件
使用tempfile.TemporaryDirectory()作为td:
f_name=os.path.join(td,“test”)
开放式(f_名称,“w”)为fh:
fh.写入(“”)
#现在文件已写入并关闭,可用于读取。

我从未使用过临时文件,您有没有理由不使用标准的
open()
write
read
方法?我想防止文件名已经存在,我可能会覆盖它1。您是否考虑过简单地将一个脚本的输出管道化到第二个脚本的输入中?2.您是否正在检查以确保临时文件存在于正在查找的路径中?您的作用域有问题。临时文件
tmp
仅存在于创建它的
循环的
范围内。请将您的评论作为答案发布,Pierce Darragh,以便我可以修改它。谢谢您解决了它。.seek(0)完成了什么?这就是您正在谈论的倒带吗?在您
tmp.writelines
之后,文件指针位于文件的末尾
tmp.seek(0)
将其重新放回开头(倒带-可能这是古老的盒式磁带行话!),这样您就可以读取您所写的内容。如果您要在不关闭并重新打开文件的情况下读取文件,请确保在写入文件后添加“f.seek(0)”。否则,您将读取文件的结尾,这将给您错误的结果。在尝试打开临时文件时,我的权限被拒绝file@CGFoX我认为,这表明您的文件系统存在一些问题。您的操作系统有一个临时文件的默认位置,这就是Python用于这些文件的位置。例如,在macOS 10.14 Mojave(我相信还有其他版本)上,位置是
/var/folders/
。如果您遇到权限被拒绝的错误,您可能没有对此位置的写入权限。或者从pathlib导入路径
然后从pathlib导入路径
f_name=Path(td)/“test”