Python - 从临时文件中写入和读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39983886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - writing and reading from a temporary file
提问by d.griner
I am trying to create a temporary file that I write in some lines from another file and then make some objects from the data. I am not sure how to find and open the temp file so I can read it. My code:
我正在尝试创建一个临时文件,我在另一个文件的某些行中写入该文件,然后从数据中创建一些对象。我不知道如何找到并打开临时文件,以便我可以阅读它。我的代码:
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()
Essentially I just want to make a middleman temporary document to protect against accidentally overwriting a file.
本质上,我只想制作一个中间人临时文件,以防止意外覆盖文件。
采纳答案by tdelaney
As per the docs, the file is deleted when the TemporaryFile
is closed and that happens when you exit the with
clause. So... don't exit the with
clause. Rewind the file and do your work in the with
.
根据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)
回答by Pierce Darragh
You've got a scope problem; the file tmp
only exists within the scope of the with
statement which creates it. Additionally, you'll need to use a NamedTemporaryFile
if you want to access the file later outside of the initial with
(this gives the OS the ability to access the file). Also, I'm not sure why you're trying to append to a temporary file... since it won't have existed before you instantiate it.
你有一个范围问题;该文件tmp
仅存在于with
创建它的语句的范围内。此外,NamedTemporaryFile
如果您想稍后在初始之外访问该文件,则需要使用 a with
(这使操作系统能够访问该文件)。另外,我不确定您为什么要尝试附加到临时文件...因为在实例化它之前它不存在。
Try this:
尝试这个:
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
回答by a_guest
In case the file needs to be opened a second time, e.g. read by a different process this might cause trouble on Windows OS:
如果文件需要再次打开,例如由不同的进程读取,这可能会导致 Windows 操作系统出现问题:
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).
在命名的临时文件仍处于打开状态时,是否可以使用该名称再次打开该文件,因平台而异(在 Unix 上可以如此使用;在 Windows NT 或更高版本上则不能)。
Hence a safe solution is to create a temporary directoryinstead and then manually create a file therein:
因此,一个安全的解决方案是创建一个临时目录,然后在其中手动创建一个文件:
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.