我应该什么时候使用tempfi

2024-10-01 09:36:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于Pythontempfile的快速问题。在

我什么时候该用临时文件?如果我使用tempfile.mkstemp创建一个临时文件,这和普通文件一样吗?有什么区别?谢谢。在


Tags: 文件tempfile区别mkstemppythontempfile
3条回答

documentation几乎说明了一切。在我看来,当您需要创建一个文件但不关心其名称时,应该使用tempfile。如果您愿意,您可以在完成或保存文件时自动将其删除。它也可以对其他程序可见或不可见。在

来自Learning Python

使用临时文件

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.

这篇文章很好地解释了它的用途。在

http://pythoncentral.org/using-the-python-tempfile-module/

第一段提供了一个很好的总结

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.

相关问题 更多 >