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()