新聞中心
今天就跟大家聊聊有關(guān)使用tempfile庫怎么創(chuàng)建一個python進程中的臨時文件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
tempfile庫的使用
tempfile
一般是python內(nèi)置的一個函數(shù)庫,不需要單獨安裝,這里我們直接介紹一下其常規(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í)行的任務(wù)為:使用tempfile.NamedTemporaryFile
創(chuàng)建一個臨時文件,其文件名采用的是隨機化的字符串格式,作為name
這樣的一個屬性來調(diào)用。通過執(zhí)行這個任務(wù),我們可以查看一般是生成什么樣格式的臨時文件:
[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í)行過程中,產(chǎn)生了tmppetcksa8
這樣的一個文件,我們可以向這個文件中直接write
一些字符串。這個臨時文件被存儲在tmp
目錄下,與當(dāng)前的執(zhí)行路徑無關(guān)。同時執(zhí)行結(jié)束之后我們發(fā)現(xiàn),產(chǎn)生的這個臨時文件被刪除了,這是NamedTemporaryFile
自帶的一個delete
的屬性,默認配置是關(guān)閉臨時文件后直接刪除。
持久化保存臨時文件
需要持久化保存臨時文件是非常容易的,只需要將上述章節(jié)中的delete
屬性設(shè)置為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
這一設(shè)定,這個設(shè)定可以允許我們持久化的存儲臨時文件:
[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!
設(shè)置臨時文件后綴
在有些場景下對于臨時文件的存儲有一定的格式要求,比如后綴等,這里我們將臨時文件的后綴設(shè)置為常用的txt
格式,同樣的,只需要在NamedTemporaryFile
的參數(shù)中進行配置即可:
# 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)
由于還是設(shè)置了delete=True
參數(shù),因此該臨時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!
看完上述內(nèi)容,你們對使用tempfile庫怎么創(chuàng)建一個python進程中的臨時文件有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
當(dāng)前文章:使用tempfile庫怎么創(chuàng)建一個python進程中的臨時文件-創(chuàng)新互聯(lián)
文章鏈接:http://www.ef60e0e.cn/article/dehoie.html