如何正確使用Python臨時(shí)文件
1.前言
臨時(shí)文件通常用來保存無法保存在內(nèi)存中的數(shù)據(jù),或者傳遞給必須從文件讀取的外部程序。一般我們會(huì)在/tmp目錄下生成唯一的文件名,但是安全的創(chuàng)建臨時(shí)文件并不是那么簡(jiǎn)單,需要遵守許多規(guī)則。永遠(yuǎn)不要自己去嘗試做這件事,而是要借助庫(kù)函數(shù)實(shí)現(xiàn)。而且也要小心清理臨時(shí)文件。
臨時(shí)文件引起的最大問題就是,可以預(yù)測(cè)文件名,導(dǎo)致惡意用戶可以預(yù)測(cè)臨時(shí)文件名,從而創(chuàng)建軟鏈接劫持臨時(shí)文件。
2. tempfile模塊介紹
創(chuàng)建臨時(shí)文件一般使用的模塊就是tempfile,此模塊庫(kù)函數(shù)常用的有以下幾個(gè):
tempfile.mktemp # 不安全,禁止使用
tempfile.mkstemp # 隨機(jī)創(chuàng)建tmp文件,默認(rèn)創(chuàng)建的文件在/tmp目錄,當(dāng)然也可以指定(可以使用)
tempfile.TemporaryFile # 內(nèi)存中創(chuàng)建文件,文件不會(huì)存儲(chǔ)在磁盤,關(guān)閉后即刪除(可以使用)
tempfile.NamedTemporaryFile(delete=True) 當(dāng)delete=True時(shí),作用跟上面一樣,當(dāng)是False時(shí),會(huì)存儲(chǔ)在磁盤(可以使用)
3. 示例介紹
以下幾種方式分別介紹了安全的創(chuàng)建臨時(shí)文件及不安全的方式。
3.1 不正確示例:
不正確1:
import os import tempfile # This will most certainly put you at risk tmp = os.path.join(tempfile.gettempdir(), filename) if not os.path.exists(tmp): with open(tmp, "w") file: file.write("defaults")
不正確2:
import os import tempfile open(tempfile.mktemp(), "w")
不正確3:
filename = "{}/{}.tmp".format(tempfile.gettempdir(), os.getpid()) open(filename, "w")
3.2 正確示例
正確1:
fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'w') as tmp: # do stuff with temp file tmp.write('stuff') finally: os.remove(path)
正確2:
句柄關(guān)閉,文件即刪除
with tempfile.TemporaryFile() as tmp: # Do stuff with tmp tmp.write('stuff')
正確3:
tmp = tempfile.NamedTemporaryFile(delete=True) try: # do stuff with temp tmp.write('stuff') finally: tmp.close() # 文件關(guān)閉即刪除
Python
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請(qǐng)聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。