这篇文章主要介绍了Python tempfile模块学习笔记,着重讲解了模块下的几个函数,需要的朋友可以参考下
tempfile.TemporaryFile
如何你的应用程序需要一个临时文件来存储数据,但不需要同其他程序共享,那么用TemporaryFile函数创建临时文件是最好的选择。其他的应用程序是无法找到或打开这个文件的,因为它并没有引用文件系统表。用这个函数创建的临时文件,关闭后会自动删除。
实例一:
import tempfile
print ‘Building a file name yourself:’
filename = ‘/tmp/guess_my_name.%s.txt’ % os.getpid()
temp = open(filename, ‘w+b’)
try:
print ‘temp:’, temp
print ‘temp.name:’, temp.name
finally:
temp.close()
os.remove(filename) # Clean up the来源gao@!dai!ma.com搞$$代^@码网 temporary file yourself
print
print ‘TemporaryFile:’
temp = tempfile.TemporaryFile()
try:
print ‘temp:’, temp
print ‘temp.name:’, temp.name
finally:
temp.close() # Automatically cleans up the file
这个例子说明了普通创建文件的方法与TemporaryFile()的不同之处,注意:用TemporaryFile()创建的文件没有文件名
输出:
Building a file name yourself:
temp:
temp.name: /tmp/guess_my_name.14932.txt
TemporaryFile:
temp: <open file '’, mode ‘w+b’ at 0x1004486f0>
temp.name:
以上就是Python tempfile模块学习笔记(临时文件)的详细内容,更多请关注gaodaima搞代码网其它相关文章!