Python tempfile模塊學(xué)習(xí)筆記(臨時(shí)文件)
tempfile.TemporaryFile
如何你的應(yīng)用程序需要一個(gè)臨時(shí)文件來(lái)存儲(chǔ)數(shù)據(jù),但不需要同其他程序共享,那么用TemporaryFile函數(shù)創(chuàng)建臨時(shí)文件是最好的選擇。其他的應(yīng)用程序是無(wú)法找到或打開(kāi)這個(gè)文件的,因?yàn)樗](méi)有引用文件系統(tǒng)表。用這個(gè)函數(shù)創(chuàng)建的臨時(shí)文件,關(guān)閉后會(huì)自動(dòng)刪除。
實(shí)例一:
import os
import tempfile
print 'Building a file name yourself:'
filename = '/tmp/guess_my_name.%s.txt' % os.getpid()
temp = open(filename, 'w+b')
try:
print 'temp:', temp
print 'temp.name:', temp.name
finally:
temp.close()
os.remove(filename) # Clean up the temporary file yourself
print 'TemporaryFile:'
temp = tempfile.TemporaryFile()
try:
print 'temp:', temp
print 'temp.name:', temp.name
finally:
temp.close() # Automatically cleans up the file
這個(gè)例子說(shuō)明了普通創(chuàng)建文件的方法與TemporaryFile()的不同之處,注意:用TemporaryFile()創(chuàng)建的文件沒(méi)有文件名
輸出:
$ python tempfile_TemporaryFile.py
Building a file name yourself:
temp: <open file '/tmp/guess_my_name.14932.txt', mode 'w+b' at 0x1004481e0>
temp.name: /tmp/guess_my_name.14932.txt
TemporaryFile:
temp: <open file '<fdopen>', mode 'w+b' at 0x1004486f0>
temp.name: <fdopen>
默認(rèn)情況下使用w+b權(quán)限創(chuàng)建文件,在任何平臺(tái)中都是如此,并且程序可以對(duì)它進(jìn)行讀寫(xiě)。這個(gè)例子說(shuō)明了普通創(chuàng)建文件的方法與TemporaryFile()的不同之處,注意:用TemporaryFile()創(chuàng)建的文件沒(méi)有文件名
$ python tempfile_TemporaryFile.py
Building a file name yourself:
temp: <open file '/tmp/guess_my_name.14932.txt', mode 'w+b' at 0x1004481e0>
temp.name: /tmp/guess_my_name.14932.txt
TemporaryFile:
temp: <open file '<fdopen>', mode 'w+b' at 0x1004486f0>
temp.name: <fdopen>
默認(rèn)情況下使用w+b權(quán)限創(chuàng)建文件,在任何平臺(tái)中都是如此,并且程序可以對(duì)它進(jìn)行讀寫(xiě)。
實(shí)例二:
import os
import tempfile
temp = tempfile.TemporaryFile()
try:
temp.write('Some data')
temp.seek(0)
print temp.read()
finally:
temp.close()
寫(xiě)入侯,需要使用seek(),為了以后讀取數(shù)據(jù)。
輸出:
$ python tempfile_TemporaryFile_binary.py
Some data
如果你想讓文件以text模式運(yùn)行,那么在創(chuàng)建的時(shí)候要修改mode為'w+t'。
實(shí)例三:
import tempfile
f = tempfile.TemporaryFile(mode='w+t')
try:
f.writelines(['first\n', 'second\n'])
f.seek(0)
for line in f:
print line.rstrip()
finally:
f.close()
輸出:
$ python tempfile_TemporaryFile_text.py
first
second
tempfile.NamedTemporaryFile
如果臨時(shí)文件會(huì)被多個(gè)進(jìn)程或主機(jī)使用,那么建立一個(gè)有名字的文件是最簡(jiǎn)單的方法。這就是NamedTemporaryFile要做的,可以使用name屬性訪問(wèn)它的名字
import os
import tempfile
temp = tempfile.NamedTemporaryFile()
try:
print 'temp:', temp
print 'temp.name:', temp.name
finally:
# Automatically cleans up the file
temp.close()
print 'Exists after close:', os.path.exists(temp.name)
盡管文件帶有名字,但它仍然會(huì)在close后自動(dòng)刪除
輸出:
$ python tempfile_NamedTemporaryFile.py
temp: <open file '<fdopen>', mode 'w+b' at 0x1004481e0>
temp.name: /var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmp0zHZvX
Exists after close: False
tempfile.mkdtemp
創(chuàng)建臨時(shí)目錄,這個(gè)不多說(shuō),直接看例子:
import os
import tempfile
directory_name = tempfile.mkdtemp()
print directory_name
# Clean up the directory yourself
os.removedirs(directory_name)
輸出
$ python tempfile_mkdtemp.py
/var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmpB1CR8M
注意:目錄需要手動(dòng)刪除。
Predicting Names
用3個(gè)參數(shù)來(lái)控制文件名,名字產(chǎn)生公式:dir + prefix + random + suffix
實(shí)例:
import tempfile
temp = tempfile.NamedTemporaryFile(suffix='_suffix',
prefix='prefix_',
dir='/tmp',
)
try:
print 'temp:', temp
print 'temp.name:', temp.name
finally:
temp.close()
輸出:
$ python tempfile_NamedTemporaryFile_args.py
temp: <open file '<fdopen>', mode 'w+b' at 0x1004481e0>
temp.name: /tmp/prefix_UyCzjc_suffix
tempfile.mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])
mkstemp方法用于創(chuàng)建一個(gè)臨時(shí)文件。該方法僅僅用于創(chuàng)建臨時(shí)文件,調(diào)用tempfile.mkstemp函數(shù)后,返回包含兩個(gè)元素的元組,第一個(gè)元素指示操作該臨時(shí)文件的安全級(jí)別,第二個(gè)元素指示該臨時(shí)文件的路徑。參數(shù)suffix和prefix分別表示臨時(shí)文件名稱的后綴和前綴;dir指定了臨時(shí)文件所在的目錄,如果沒(méi)有指定目錄,將根據(jù)系統(tǒng)環(huán)境變量TMPDIR, TEMP或者TMP的設(shè)置來(lái)保存臨時(shí)文件;參數(shù)text指定了是否以文本的形式來(lái)操作文件,默認(rèn)為False,表示以二進(jìn)制的形式來(lái)操作文件。
tempfile.mktemp([suffix=''[, prefix='tmp'[, dir=None]]])
mktemp用于返回一個(gè)臨時(shí)文件的路徑,但并不創(chuàng)建該臨時(shí)文件。
tempfile.tempdir
該屬性用于指定創(chuàng)建的臨時(shí)文件(夾)所在的默認(rèn)文件夾。如果沒(méi)有設(shè)置該屬性或者將其設(shè)為None,Python將返回以下環(huán)境變量TMPDIR, TEMP, TEMP指定的目錄,如果沒(méi)有定義這些環(huán)境變量,臨時(shí)文件將被創(chuàng)建在當(dāng)前工作目錄。
tempfile.gettempdir()
gettempdir()則用于返回保存臨時(shí)文件的文件夾路徑。
相關(guān)文章
Python強(qiáng)制重新安裝Python包之pip的高級(jí)使用技巧
這篇文章主要介紹了如何使用pip強(qiáng)制重新安裝Python包的幾種方法,包括使用--upgrade、--force-reinstall和--no-deps選項(xiàng),這些方法可以幫助解決包損壞、依賴問(wèn)題或其他需要重新安裝包的情況,需要的朋友可以參考下2025-03-03
基于Python OpenCV實(shí)現(xiàn)圖像的覆蓋
本文將基于Python、OpenCV和Numpy實(shí)現(xiàn)圖像的覆蓋,即小圖像覆蓋在大圖像上。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-02-02
python打印n位數(shù)“水仙花數(shù)”(實(shí)例代碼)
這篇文章主要介紹了python打印n位數(shù)“水仙花數(shù)”,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12
python服務(wù)器與android客戶端socket通信實(shí)例
這篇文章主要介紹了python服務(wù)器與android客戶端socket通信的實(shí)現(xiàn)方法,實(shí)例形式詳細(xì)講述了Python的服務(wù)器端實(shí)現(xiàn)原理與方法,以及對(duì)應(yīng)的Android客戶端實(shí)現(xiàn)方法,需要的朋友可以參考下2014-11-11
如何使用python生成大量數(shù)據(jù)寫(xiě)入es數(shù)據(jù)庫(kù)并查詢操作
這篇文章主要介紹了如何使用python生成大量數(shù)據(jù)寫(xiě)入es數(shù)據(jù)庫(kù)并查詢操作,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
Python數(shù)據(jù)清洗之利用pandas篩選數(shù)據(jù)詳解
這篇文章主要介紹了Python數(shù)據(jù)清洗之利用pandas篩選數(shù)據(jù)詳解,Pandas是一個(gè)用于數(shù)據(jù)分析和處理的Python庫(kù),它提供了高效的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)分析工具,使得數(shù)據(jù)的清洗、轉(zhuǎn)換、分析和可視化變得更加容易和靈活,需要的朋友可以參考下2023-08-08
基于python的selenium兩種文件上傳操作實(shí)現(xiàn)詳解
這篇文章主要介紹了基于python的selenium兩種文件上傳操作實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09

