欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

使用tempfile庫怎么創(chuàng)建一個python進程中的臨時文件-創(chuàng)新互聯

今天就跟大家聊聊有關使用tempfile庫怎么創(chuàng)建一個python進程中的臨時文件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

網站建設哪家好,找創(chuàng)新互聯建站!專注于網頁設計、網站建設、微信開發(fā)、微信平臺小程序開發(fā)、集團企業(yè)網站建設等服務項目。為回饋新老客戶創(chuàng)新互聯還提供了徐聞免費建站歡迎大家使用!

tempfile庫的使用

tempfile一般是python內置的一個函數庫,不需要單獨安裝,這里我們直接介紹一下其常規(guī)使用方法:

# tempfile_test.py

import tempfile

file = tempfile.NamedTemporaryFile()
name = str(file.name)
file.write('This is the first tmp file!'.encode('utf-8'))
file.close()

print (name)

上述代碼執(zhí)行的任務為:使用tempfile.NamedTemporaryFile創(chuàng)建一個臨時文件,其文件名采用的是隨機化的字符串格式,作為name這樣的一個屬性來調用。通過執(zhí)行這個任務,我們可以查看一般是生成什么樣格式的臨時文件:

[dechin@dechin-manjaro tmp_file]$ python3 tempfile_test.py 
/tmp/tmppetcksa8
[dechin@dechin-manjaro tmp_file]$ ll
總用量 4
-rw-r--r-- 1 dechin dechin 181 1月 27 21:39 tempfile_test.py
[dechin@dechin-manjaro tmp_file]$ cat /tmp/tmppetcksa8
cat: /tmp/tmppetcksa8: 沒有那個文件或目錄

在這個python代碼的執(zhí)行過程中,產生了tmppetcksa8這樣的一個文件,我們可以向這個文件中直接write一些字符串。這個臨時文件被存儲在tmp目錄下,與當前的執(zhí)行路徑無關。同時執(zhí)行結束之后我們發(fā)現,產生的這個臨時文件被刪除了,這是NamedTemporaryFile自帶的一個delete的屬性,默認配置是關閉臨時文件后直接刪除。

持久化保存臨時文件

需要持久化保存臨時文件是非常容易的,只需要將上述章節(jié)中的delete屬性設置為False即可:

# tempfile_test.py

import tempfile

file = tempfile.NamedTemporaryFile(delete=False)
name = str(file.name)
file.write('This is the first tmp file!'.encode('utf-8'))
file.close()

print (name)

這里我們的變動,只是在括號中加上了delete=True這一設定,這個設定可以允許我們持久化的存儲臨時文件:

[dechin@dechin-manjaro tmp_file]$ python3 tempfile_test.py 
/tmp/tmpwlt27ryk
[dechin@dechin-manjaro tmp_file]$ cat /tmp/tmpwlt27ryk
This is the first tmp file!

設置臨時文件后綴

在有些場景下對于臨時文件的存儲有一定的格式要求,比如后綴等,這里我們將臨時文件的后綴設置為常用的txt格式,同樣的,只需要在NamedTemporaryFile的參數中進行配置即可:

# tempfile_test.py

import tempfile

file = tempfile.NamedTemporaryFile(delete=False, suffix='.txt')
name = str(file.name)
file.write('This is the first tmp file!'.encode('utf-8'))
file.close()

print (name)

由于還是設置了delete=True參數,因此該臨時txt文件被持久化的保存在系統(tǒng)中的/tmp目錄下:

[dechin@dechin-manjaro tmp_file]$ python3 tempfile_test.py 
/tmp/tmpk0ct_kzs.txt
[dechin@dechin-manjaro tmp_file]$ cat /tmp/tmpk0ct_kzs.txt
This is the first tmp file!

看完上述內容,你們對使用tempfile庫怎么創(chuàng)建一個python進程中的臨時文件有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創(chuàng)新互聯行業(yè)資訊頻道,感謝大家的支持。

文章名稱:使用tempfile庫怎么創(chuàng)建一個python進程中的臨時文件-創(chuàng)新互聯
當前路徑:http://www.chinadenli.net/article4/dehoie.html

成都網站建設公司_創(chuàng)新互聯,為您提供響應式網站標簽優(yōu)化外貿建站移動網站建設搜索引擎優(yōu)化網站策劃

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯

微信小程序開發(fā)