Python 使用tempfile包輕松無痕的運行代碼
一、簡介
這里介紹python中臨時文件及文件夾使用。
使用的是tempfile包:
pip install tempfile
https://docs.python.org/3/library/tempfile.html
二、臨時文件夾
2.1 獲取臨時文件夾
# 獲取臨時文件夾 tmpdir = tempfile.gettempdir() print(tmpdir) #/tmp
2.2 生成臨時文件夾
# 方式一:生成默認(rèn)臨時文件夾 tmpdir = tempfile.mkdtemp() print(tmpdir) #/tmp/tmpui77cgud # 方式二:生成自定義臨時文件夾(指定前綴、后綴、目錄,可指定其中一部分),suffix:后綴, prefix:前綴, dir:目錄 tmpdir = tempfile.mkdtemp(suffix='_txt', prefix='tp_dir_', dir='/home/tmp/py_rs_file') print(tmpdir) # /home/tmp/py_rs_file/tp_dir_06l_o2dm_txt
三、臨時文件
3.1 生成不自動刪除(關(guān)閉時)的臨時文件
# 方式一:生成默認(rèn)臨時文件,默認(rèn)為二進(jìn)制文件
tmpfile = tempfile.mkstemp()[1]
print(tempfile) #/tmp/tmp75kazf_8
# 數(shù)據(jù)寫入
with open(tmpfile, 'w+') as t_f:
t_f.writelines('hello world')
# 方式二:生成自定義臨時文件(指定前綴、后綴、目錄、文件類型參數(shù),可指定其中一部分),suffix:后綴, prefix:前綴, dir:目錄, text:文件類型,True為文本,false為二進(jìn)制
tmpfile = tempfile.mkstemp(suffix='.txt', prefix='tp_', dir='/home/tmp/py_rs_file', text=True)[1]
print(tempfile) # /home/tmp/py_rs_file/tp_pn2973g0.txt
# 數(shù)據(jù)寫入
with open(tmpfile, 'w+') as t_f:
t_f.writelines('hello world')
3.2 生成自動刪除的臨時文件
# 方式一:創(chuàng)建臨時文件,文件關(guān)閉時自動刪除
tmpfile = tempfile.TemporaryFile(mode='w+t')
tmpfile.write('hello world') ##數(shù)據(jù)寫入
tmpfile.seek(0)
tmpTxt = tmpfile.read() #數(shù)據(jù)讀取
print(tmpTxt)
tmpfile.close() #關(guān)閉時文件自動刪除
# 方式二:創(chuàng)建臨時文件,文件關(guān)閉時根據(jù)delete參數(shù)確定是否自動刪除, True:刪除 False:不刪除
with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
file_name = tmpfile.name
print(file_name) #/tmp/tmp73zl8gmn
tmpfile.write('hello world'.encode())
tmpfile.seek(0)
tmpTxt = tmpfile.read().decode()
print(tmpTxt)
# 方式三:創(chuàng)建自定義臨時文件,文件關(guān)閉時可根據(jù)delete參數(shù)確定是否自動刪除, True:刪除 False:不刪除
# 其他配置參數(shù)有,mode:文件模式(w+b為二進(jìn)制模式(默認(rèn)),w+t為文本模式),suffix:后綴, prefix:前綴, dir:目錄
with tempfile.NamedTemporaryFile(mode='w+t', suffix='.txt', prefix='tp_', dir='/home/tmp/py_rs_file',delete=False) as tmpfile:
file_name = tmpfile.name
print(file_name) #/home/tmp/py_rs_file/tp_fcwpmh3l.txt
tmpfile.write('hello world')
tmpfile.seek(0)
tmpTxt = tmpfile.read()
print(tmpTxt)
根據(jù)具體情況,臨時資源可以直接調(diào)用內(nèi)存或數(shù)據(jù)庫存儲。
技術(shù)交流
歡迎轉(zhuǎn)載、收藏、有所收獲點贊支持一下!

到此這篇關(guān)于Python 使用tempfile包輕松無痕的運行代碼的文章就介紹到這了,更多相關(guān)Python tempfile包內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信