正確的使用Python臨時(shí)文件
臨時(shí)文件通常用來保存無法保存在內(nèi)存中的數(shù)據(jù),或者傳遞給必須從文件讀取的外部程序。一般我們會在/tmp目錄下生成唯一的文件名,但是安全的創(chuàng)建臨時(shí)文件并不是那么簡單,需要遵守許多規(guī)則。永遠(yuǎn)不要自己去嘗試做這件事,而是要借助庫函數(shù)實(shí)現(xiàn)。而且也要小心清理臨時(shí)文件。
臨時(shí)文件引起的最大問題就是,可以預(yù)測文件名,導(dǎo)致惡意用戶可以預(yù)測臨時(shí)文件名,從而創(chuàng)建軟鏈接劫持臨時(shí)文件。
2. tempfile模塊介紹創(chuàng)建臨時(shí)文件一般使用的模塊就是tempfile,此模塊庫函數(shù)常用的有以下幾個:
tempfile.mktemp # 不安全,禁止使用tempfile.mkstemp # 隨機(jī)創(chuàng)建tmp文件,默認(rèn)創(chuàng)建的文件在/tmp目錄,當(dāng)然也可以指定(可以使用)tempfile.TemporaryFile # 內(nèi)存中創(chuàng)建文件,文件不會存儲在磁盤,關(guān)閉后即刪除(可以使用)tempfile.NamedTemporaryFile(delete=True) 當(dāng)delete=True時(shí),作用跟上面一樣,當(dāng)是False時(shí),會存儲在磁盤(可以使用)
3. 示例介紹以下幾種方式分別介紹了安全的創(chuàng)建臨時(shí)文件及不安全的方式。
3.1 不正確示例:不正確1:
import osimport tempfile # This will most certainly put you at risktmp = os.path.join(tempfile.gettempdir(), filename)if not os.path.exists(tmp): with open(tmp, 'w') file: file.write('defaults')
不正確2:
import osimport 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臨時(shí)文件的詳細(xì)內(nèi)容,更多關(guān)于使用Python臨時(shí)文件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
