最佳答案
我正在编写一个 Python 脚本,它需要创建大约50个不同的临时文件,这些文件在脚本编写过程中经常被添加,并在最后合并。我确信 tempfile
模块可以满足我的需要,但是我还不能从阅读文档中了解如何做到这一点。
我想使用临时文件——而不是变量——来节省系统内存,因为这些数据块随着脚本处理成千上万个其他文件而变大。
下面这段代码是我目前用来在非临时目录中创建这些文件(非临时)的代码:
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)
我想我需要的是 tempfile.NamedTemporaryFile()
。根据 文件:
可以从文件对象的名称成员中检索该名称。
不幸的是,我不明白这是什么意思。我只是需要能够再次调用每个文件后,当我运行对应的“项目”再次在我处理的文件。我觉得这很直接,我只是有点迟钝。如果有必要的话,我为 Python 2.7.1和3.2.3都准备了这个脚本的版本。我只需要其中一个来工作; 我创建这两个只是作为一个学习练习。