stackoverflow中的问题编号10501247给出了如何在Python中创建临时文件的答案.
在我的情况下,我只需要有临时文件名.
调用tempfile.NamedTemporaryFile()会在实际创建文件后返回文件句柄.
有办法获取文件名吗?
# Trying to get temp file path
tf = tempfile.NamedTemporaryFile()
temp_file_name = tf.name
tf.close()
# Here is my real purpose to get the temp_file_name
f = gzip.open(temp_file_name ,'wb')
...
Run Code Online (Sandbox Code Playgroud) 我正在开发一个Python脚本,需要创建大约50个不同的临时文件,这些文件在脚本过程中经常被附加并在最后合并.我确信该tempfile模块可以做我需要的,但我无法弄清楚如何阅读文档.
我想使用临时文件(而不是变量)来节省系统内存,因为这些数据块会随着脚本处理数万个其他文件而变大.
下面的代码块是我正在用于在非临时目录中创建这些文件(非暂时)的hack:
item = (string from another file) # string must id file for future use
tmpfile = 'tmpfiles/' + item
if item not in totalitems:
totalitems.add(item)
with open(tmpfile, 'w') as itemfile:
output = some stuff
tmpfile.write(output)
else:
with open(tmpfile, 'a') as itemfile:
output = different stuff
tmpfile.write(output)
Run Code Online (Sandbox Code Playgroud)
我想我需要的是tempfile.NamedTemporaryFile().根据文件:
可以从文件对象的名称成员中检索该名称.
不幸的是,我不明白这意味着什么.当我在我正在处理的文件中再次运行其相应的"项目"时,我只需要能够稍后再次调用每个文件.我认为这是相当直接的,我只是在密集.如果它很重要,我有Python 2.7.1和3.2.3的这个脚本的版本.我真的只需要一个人或另一个人去工作; 我创造了两个作为学习练习.