日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python tempfile cleanup_python tempfile 模块---生成临时文件和目录

發布時間:2023/12/19 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python tempfile cleanup_python tempfile 模块---生成临时文件和目录 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 tempfile介紹

tempfile 模塊中常用的函數,如下表所示。

tempfile 模塊函數功能描述tempfile.TemporaryFile(mode=‘w+b’, buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)創建臨時文件。該函數返回一個類文件對象,也就是支持文件 I/O。

tempfile.NamedTemporaryFile(mode=‘w+b’, buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True)創建臨時文件。該函數的功能與上一個函數的功能大致相同,只是它生成的臨時文件在文件系統中有文件名。

tempfile.SpooledTemporaryFile(max_size=0, mode=‘w+b’, buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)創建臨時文件。與 TemporaryFile 函數相比,當程序向該臨時文件輸出數據時,會先輸出到內存中,直到超過 max_size 才會真正輸出到物理磁盤中。

tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)生成臨時目錄。

tempfile.gettempdir()獲取系統的臨時目錄。

tempfile.gettempdirb()與 gettempdir() 相同,只是該函數返回字節串。

tempfile.gettempprefix()返回用于生成臨時文件的前綴名。

tempfile.gettempprefixb()與 gettempprefix() 相同,只是該函數返回字節串。

提示:表中有些函數包含很多參數,但這些參數都具有自己的默認值,因此如果沒有特殊要求,可以不對其傳參。

2 創建臨時文件

2.1 TemporaryFile

該函數返回一個類文件對象,用于臨時數據保存(實際上對應磁盤上的一個臨時文件)。

def TemporaryFile(mode='w+b', buffering=-1, encoding=None,

newline=None, suffix=None, prefix=None,

dir=None, *, errors=None)

生成的對象可以用作上下文管理器。完成文件對象的上下文或銷毀后(文件對象被 close 或者被 del),臨時文件將從文件系統中刪除。

mode 參數默認值為 w+b,采用二進制模式,可以進行讀寫

buffering 用于設置緩沖策略。0:關閉緩沖(僅允許在二進制模式下),1:行緩沖(僅在文本模式下可用),>1 的整數:指定塊緩沖區的大小(以字節為單位)。如果沒有給出 buffering 參數,采用默認緩沖策略

encoding 是用于解碼或編碼文件的編碼的名稱

prefix 指定了臨時文件名的前綴

suffix 指定了臨時文件名的后綴

dir 用于設置臨時文件默認的保存路徑

返回的類文件對象有一個 file 屬性,它指向真正操作的底層的 file 對象

from tempfile import TemporaryFile

temp = TemporaryFile(dir='/home/skx/pra')

print(temp)

print(temp.name)

'''

TemporaryFile類的構造方法,其返回的還是一個文件對象。但這個文件對象特殊的地方在于

1. 對應的文件沒有文件名,對除了本程序之外的程序不可見

2. 在被關閉的同時被刪除

所以上面的兩句打印語句,輸出分別是一個文件對象,以及一個(并不是文件名)

'''

# 向臨時文件中寫入內容

temp.write(b'hello\nworld')

temp.seek(0) # 將文件指針移動到頭部,準備讀取文件

print(temp.read())

temp.close() # 關閉文件的同時刪除文件

# 通過with語句創建臨時文件,with會自動關閉臨時文件

with TemporaryFile() as fd:

fd.write("我最棒".encode('utf-8'))

fd.seek(0)

print(fd.read().decode('utf-8'))

3

b'hello\nworld'

我最棒

注意:mode 參數默認值為 w+b,寫 str 時每次需要轉換為 binary 再寫入,這樣很麻煩,可以指定打開方式為 w+,這樣就可以直接進行 str 類型的讀寫了

讀取配置文件放入臨時文件

example.ini

[DEFAULT]

ip = 172.0.0.1

port = 22

[bitbucket.org]

user = Atlan

conf_tempfile.py

#coding=utf-8

import configparser

from tempfile import TemporaryFile

conf = configparser.ConfigParser()

conf.read('example.ini')

with TemporaryFile(mode='w+') as fd:

conf.write(fd) # 注意這里的用法

fd.seek(0)

print(fd.read())

2.2 NamedTemporaryFile

此函數執行的操作與 TemporaryFile() 完全相同,但是創建的臨時文件有文件名,在文件系統中可以找到,因此可以多個進程同時訪問

def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,

newline=None, suffix=None, prefix=None,

dir=None, delete=True, *, errors=None)

該函數多了一個 delete 參數,用于指定類文件對象 close 或者被 del 之后,是否也一同刪除磁盤上的臨時文件(當 delete = True 的時候,行為與 TemporaryFile 一樣)。

import os

from tempfile import NamedTemporaryFile

# 指定文件以 "head_" 開頭,以"_tail"結尾

temp = NamedTemporaryFile(suffix="_tail", prefix="head_", dir='/home/skx/pra',delete=False)

try:

print('temp:', temp)

print('temp.name:', temp.name)

finally:

temp.close()

# 指定了delete,文件對象 close 或者被 del 之后,磁盤文件不會被刪除

print('Exists after close:', os.path.exists(temp.name))

運行結果:

temp:

temp.name: /home/skx/pra/head_0dsw2361_tail

Exists after close: True

指定 delete=False,文件對象 close 或者被 del 之后,不刪除磁盤上的臨時文件,在指定的目錄中可以看到文件如下

2.3 SpooledTemporaryFile

tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=-1,

encoding=None, newline=None,

suffix=None, prefix=None, dir=None, *, errors=None)

此函數執行的操作與 TemporaryFile() 完全相同,但會將數據緩存在內存中,直到文件大小超過 max_size,或調用文件的 fileno() 方法為止,此時數據會被寫入磁盤。

2.4 mkstemp

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

prefix 指定了臨時文件名的前綴

suffix 指定了臨時文件名的后綴

dir 用于設置臨時文件默認的保存路徑

text 指定了是否以文本的形式來操作文件,默認為False,表示以二進制的形式來操作文件。

mkstemp() 返回一個元組,元組中第一個元素是句柄,它是一個系統級句柄,指向一個打開的文件(等同于 os.open() 的返回值),第二元素是該文件的絕對路徑。

文件使用完后文件不會自動清除,需要手動清理。

import tempfile

tmp_f = tempfile.mkstemp(dir="/home/skx/pra/")

print(tmp_f)# (3, '/home/skx/pra/tmp58do2j53')--> tmp_f[0] 是句柄,tmp_f[1] 是文件路徑

fd = tmp_f[1]

with open(fd, 'w+') as f:

f.write('Hello world')

f.seek(0)

print(f.read())

運行結果

(3, '/home/skx/pra/tmp58do2j53')

Hello world

3 創建臨時目錄

3.1 TemporaryDirectory

tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)

prefix 指定了臨時文件名的前綴

suffix 指定了臨時文件名的后綴

dir 用于設置臨時文件默認的保存路徑

此函數會安全地創建一個臨時目錄。此函數返回的對象可用作上下文管理器。完成上下文或銷毀臨時目錄對象后,新創建的臨時目錄及其所有內容自動將從文件系統中刪除。

也可以調用 cleanup() 方法手動清理目錄。

import os

import tempfile

with tempfile.TemporaryDirectory(suffix='_tail', prefix='head_') as dir_name:

print(dir_name)

print(os.path.exists(dir_name))

運行結果

/tmp/head_gtbt2gkw_tail

False

3.2 mkdtemp

def mkdtemp(suffix=None, prefix=None, dir=None)

prefix 指定了臨時文件名的前綴

suffix 指定了臨時文件名的后綴

dir 用于設置臨時文件默認的保存路徑

以最安全的方式創建一個臨時目錄,創建該目錄時不會有競爭的情況。該目錄只能由創建者讀取、寫入和搜索。返回新目錄的絕對路徑名。

用戶用完臨時目錄后需要自行將其刪除。

import os

import tempfile

dir_name = tempfile.mkdtemp(suffix='_tail', prefix='head_', dir='/tmp')

print(dir_name)

# 需要手動清理

os.removedirs(dir_name)

運行結果

/tmp/head_kn9uoe1z_tail

原文鏈接:https://blog.csdn.net/happyjacob/article/details/112385665

總結

以上是生活随笔為你收集整理的python tempfile cleanup_python tempfile 模块---生成临时文件和目录的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。