如何用tempfile庫創(chuàng)建python進程中的臨時文件
技術背景
臨時文件在python項目中時常會被使用到,其作用在于隨機化的創(chuàng)建不重名的文件,路徑一般都是放在Linux系統(tǒng)下的/tmp目錄。如果項目中并不需要持久化的存儲一個文件,就可以采用臨時文件的形式進行存儲和讀取,在使用之后可以自行決定是刪除還是保留。
tempfile庫的使用
tempfile
一般是python內置的一個函數庫,不需要單獨安裝,這里我們直接介紹一下其常規(guī)使用方法:
# tempfile_test.py import tempfile file = tempfile.NamedTemporaryFile() name = str(file.name) file.write('This is the first tmp file!'.encode('utf-8')) file.close() print (name)
上述代碼執(zhí)行的任務為:使用tempfile.NamedTemporaryFile
創(chuàng)建一個臨時文件,其文件名采用的是隨機化的字符串格式,作為name
這樣的一個屬性來調用。通過執(zhí)行這個任務,我們可以查看一般是生成什么樣格式的臨時文件:
[dechin@dechin-manjaro tmp_file]$ python3 tempfile_test.py /tmp/tmppetcksa8 [dechin@dechin-manjaro tmp_file]$ ll 總用量 4 -rw-r--r-- 1 dechin dechin 181 1月 27 21:39 tempfile_test.py [dechin@dechin-manjaro tmp_file]$ cat /tmp/tmppetcksa8 cat: /tmp/tmppetcksa8: 沒有那個文件或目錄
在這個python代碼的執(zhí)行過程中,產生了tmppetcksa8
這樣的一個文件,我們可以向這個文件中直接write
一些字符串。這個臨時文件被存儲在tmp
目錄下,與當前的執(zhí)行路徑無關。同時執(zhí)行結束之后我們發(fā)現,產生的這個臨時文件被刪除了,這是NamedTemporaryFile
自帶的一個delete
的屬性,默認配置是關閉臨時文件后直接刪除。
持久化保存臨時文件
需要持久化保存臨時文件是非常容易的,只需要將上述章節(jié)中的delete
屬性設置為False
即可:
# tempfile_test.py import tempfile file = tempfile.NamedTemporaryFile(delete=False) name = str(file.name) file.write('This is the first tmp file!'.encode('utf-8')) file.close() print (name)
這里我們唯一的變動,只是在括號中加上了delete=True
這一設定,這個設定可以允許我們持久化的存儲臨時文件:
[dechin@dechin-manjaro tmp_file]$ python3 tempfile_test.py /tmp/tmpwlt27ryk [dechin@dechin-manjaro tmp_file]$ cat /tmp/tmpwlt27ryk This is the first tmp file!
設置臨時文件后綴
在有些場景下對于臨時文件的存儲有一定的格式要求,比如后綴等,這里我們將臨時文件的后綴設置為常用的txt
格式,同樣的,只需要在NamedTemporaryFile
的參數中進行配置即可:
# tempfile_test.py import tempfile file = tempfile.NamedTemporaryFile(delete=False, suffix='.txt') name = str(file.name) file.write('This is the first tmp file!'.encode('utf-8')) file.close() print (name)
由于還是設置了delete=True
參數,因此該臨時txt
文件被持久化的保存在系統(tǒng)中的/tmp
目錄下:
[dechin@dechin-manjaro tmp_file]$ python3 tempfile_test.py /tmp/tmpk0ct_kzs.txt [dechin@dechin-manjaro tmp_file]$ cat /tmp/tmpk0ct_kzs.txt This is the first tmp file!
總結概要
本文主要介紹了python中自帶的tempfile庫對臨時文件的操作,通過tempfile庫我們可以創(chuàng)建自動刪除的或者持久化存儲的臨時文件,存儲路徑為Linux系統(tǒng)下的/tmp目錄,而我們還可以根據不同的場景需要對產生的臨時文件的后綴進行配置。
原文鏈接為:https://www.cnblogs.com/dechinphy/p/tempfile.html
以上就是如何用tempfile庫創(chuàng)建python進程中的臨時文件的詳細內容,更多關于tempfile庫創(chuàng)建臨時文件的資料請關注腳本之家其它相關文章!
相關文章
Python中的random.uniform()函數教程與實例解析
今天小編就為大家分享一篇關于Python中的random.uniform()函數教程與實例解析,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03使用grappelli為django admin后臺添加模板
本文介紹了一款非常流行的Django模板系統(tǒng)--grappelli,以及如何給Django的admin后臺添加模板,非常的實用,這里推薦給大家。2014-11-11Python使用pymssql連接SQL?SEVER數據庫全流程
SQL Server是微軟推出的重量級的數據庫,目前有多個版本,如2000、2008、2012等,下面這篇文章主要給大家介紹了關于Python使用pymssql連接SQL?SEVER數據庫的相關資料,需要的朋友可以參考下2023-12-12pytorch中nn.Sequential和nn.Module的區(qū)別與選擇方案
在 PyTorch 中,構建神經網絡模型有兩種主要方式:nn.Sequential 和 nn.Module,它們各有優(yōu)缺點,適用于不同的場景,下面通過示例給大家講解pytorch中nn.Sequential和nn.Module的區(qū)別與選擇方案,感興趣的朋友一起看看吧2024-06-06