If you've ever written a shell script and needed to use intermediary
files for storing the results of some intermediate stages of
processing, you probably suffered from directory litter. You started
out with 20 files called log_001.txt, log_002.txt etc., and all you
wanted was one summary file called log_sum.txt. In addition, you had a
whole bunch of log_001.tmp, log_001.tm2, etc. files that, while they
were labeled temporary, stuck around. At least that's what we've seen
happen in our own lives. To put order back into your directories, use
temporary files in specific directories and clean them up afterwards.
To help in this temporary file-management problem, Python provides a
nice little module called tempfile that publishes two functions:
mktemp() and TemporaryFile(). The former returns the name of a file
not currently in use in a directory on your computer reserved for
temporary files (such as /tmp on Unix or C:\TMP on Windows). The
latter returns a new file object directly.
While programming in Python, there will likely be times where you have some data that needs to be utilized or manipulated in the form of
a file but hasn’t yet been written to one. Naturally, the first
solution that comes to mind is to open a new or existing file, write
the data and finally save it (if you’re unfamiliar with how to do this
take a look at the article Reading and Writing Files in Python).
However, it might also be the case that once your script(s) are
finished running, you don’t need or want the file(s) anymore, and
therefore, don’t want it hanging around in your or anyone else’s file
system.
documentation几乎说明了一切。在我看来,当您需要创建一个文件但不关心其名称时,应该使用
tempfile
。如果您愿意,您可以在完成或保存文件时自动将其删除。它也可以对其他程序可见或不可见。在来自Learning Python:
使用临时文件
这篇文章很好地解释了它的用途。在
http://pythoncentral.org/using-the-python-tempfile-module/
第一段提供了一个很好的总结
相关问题 更多 >
编程相关推荐