python中的tempfile模块,是为创建临时文件(夹)所提供的
如果你的应用程序需要一个临时文件来存储数据,但不需要同其他程序共享,那么tempfile模块来创建临时文件(夹)是个不错的选择
其他的应用程序是无法找到活打开这个文件(夹),因为tempfile在创建的过程中没有引用文件系统表,用tempfile创建的临时文件(夹),关闭
后会自动删除。
下面是我做的demo:
运行效果:
=====================================
代码部分:
=====================================
1 #python tempfile
2
3 '''
4 import tempfile
5
6 如何你的应用程序需要一个临时文件来存储数据,
7 但不需要同其他程序共享,那么用TemporaryFile
8 函数创建临时文件是最好的选择。其他的应用程序
9 是无法找到或打开这个文件的,因为它并没有引用
10 文件系统表。用这个函数创建的临时文件,关闭后
11 会自动删除。
12 '''
13
14 import os
15 import tempfile
16
17 def make_file():
18 '''创建临时文件,不过创建后,需要手动移除
19 os.remove(file)
20 '''
21 file_name = 'c:\\tmp\\test.%s.txt' % os.getpid()
22 temp = open(file_name, 'w+b')
23 try:
24 print('temp : {}'.format(temp))
25 print('temp.name : {}'.format(temp.name))
26 temp.write(b'hello, I\'m Hongten')
27 temp.seek(0)
28 print('#' * 50)
29 print('content : {}'.format(temp.read()))
30 finally:
31 temp.close()
32 #os.remove(file_name)
33
34 def make_temp_file():
35 '''创建临时文件,在关闭的时候,系统会自动清除文件'''
36 temp = tempfile.TemporaryFile()
37 try:
38 print('temp : {}'.format(temp))
39 print('temp.name : {}'.format(temp.name))
40 temp.write(b'hello, I\'m Hongten')
41 temp.seek(0)
42 print('#' * 50)
43 print('content : {}'.format(temp.read()))
44 finally:
45 temp.close() #then the system will automatically cleans up the file
46
47 def main():
48 make_file()
49 print('#' * 50)
50 make_temp_file()
51
52 if __name__ == '__main__':
53 main()