最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python 使用tempfile包輕松無痕的運行代碼

 更新時間:2021年11月18日 14:18:09   作者:Python學(xué)習(xí)與數(shù)據(jù)挖掘  
大家好,我們知道軟件運行過程中一般會在指定位置生成臨時文件,這些資源不要輕易刪除,可能是過程文件,定時清理是必要的,今天給大家分享一款工具:tempfile,喜歡本文點贊支持,歡迎收藏學(xué)習(xí)

一、簡介

這里介紹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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

永丰县| 丹江口市| 措美县| 独山县| 兴化市| 荣昌县| 中宁县| 健康| 锡林郭勒盟| 林甸县| 闽清县| 郧西县| 如皋市| 门源| 乌鲁木齐县| 建平县| 武清区| 岳池县| 平南县| 锡林浩特市| 曲沃县| 会泽县| 佛教| 伊吾县| 柘荣县| 明溪县| 多伦县| 罗平县| 乡宁县| 南澳县| 锡林郭勒盟| 遵化市| 石屏县| 栖霞市| 鸡泽县| 广丰县| 喀喇沁旗| 得荣县| 拜城县| 启东市| 于都县|