主要有以下几个函数:
tempfile.TemporaryFile
如何你的应用程序需要一个临时文件来存储数据,但不需要同其他程序共享,那么用TemporaryFile函数创建临时文件是最好的选择。其他的应用程序是无法找到或打开这个文件的,因为它并没有引用文件系统表。用这个函数创建的临时文件,关闭后会自动删除。
1 import os
2 import tempfile
3
4 print ‘Building a file name yourself:‘
5 filename = ‘/tmp/guess_my_name.%s.txt‘ % os.getpid()
6 temp = open(filename, ‘w+b‘)
7 try:
8 print ‘temp:‘, temp
9 print ‘temp.name:‘, temp.name
10 finally:
11 temp.close()
12 os.remove(filename) # Clean up the temporary file yourself
13
14 print
15 print ‘TemporaryFile:‘
16 temp = tempfile.TemporaryFile()
17 try:
18 print ‘temp:‘, temp
19 print ‘temp.name:‘, temp.name
20 finally:
21 temp.close() # Automatically cleans up the file
2 import tempfile
3
4 print ‘Building a file name yourself:‘
5 filename = ‘/tmp/guess_my_name.%s.txt‘ % os.getpid()
6 temp = open(filename, ‘w+b‘)
7 try:
8 print ‘temp:‘, temp
9 print ‘temp.name:‘, temp.name
10 finally:
11 temp.close()
12 os.remove(filename) # Clean up the temporary file yourself
13
14 print
15 print ‘TemporaryFile:‘
16 temp = tempfile.TemporaryFile()
17 try:
18 print ‘temp:‘, temp
19 print ‘temp.name:‘, temp.name
20 finally:
21 temp.close() # Automatically cleans up the file