python中臨時文件及文件夾使用
文章目錄
- python中臨時文件及文件夾使用
- 一、簡介
- 二、臨時文件夾
- 2.1 獲取臨時文件夾
- 2.2 生成臨時文件夾
- 三、臨時文件
- 3.1 生成不自動刪除(關閉時)的臨時文件
- 3.2 生成自動刪除的臨時文件
一、簡介
這里介紹python中臨時文件及文件夾使用。使用的是tempfile包(安裝:pip install tempfile),參考地址是https://docs.python.org/3/library/tempfile.html。
二、臨時文件夾
2.1 獲取臨時文件夾
# 獲取臨時文件夾
tmpdir
=
tempfile
.
gettempdir
(
)
print
(
tmpdir
)
#/tmp
2.2 生成臨時文件夾
# 方式一:生成默認臨時文件夾
tmpdir
=
tempfile
.
mkdtemp
(
)
print
(
tmpdir
)
#/tmp/tmpui77cgud
# 方式二:生成自定義臨時文件夾(指定前綴、后綴、目錄,可指定其中一部分),suffix:后綴, prefix:前綴, dir:目錄
tmpdir
=
tempfile
.
mkdtemp
(
suffix
=
'_txt'
,
prefix
=
'tp_dir_'
,
dir
=
'/home/china/tmp/py_rs_file'
)
print
(
tmpdir
)
# /home/china/tmp/py_rs_file/tp_dir_06l_o2dm_txt
三、臨時文件
3.1 生成不自動刪除(關閉時)的臨時文件
# 方式一:生成默認臨時文件,默認為二進制文件
tmpfile
=
tempfile
.
mkstemp
(
)
[
1
]
print
(
tempfile
)
#/tmp/tmp75kazf_8
# 數據寫入
with
open
(
tmpfile
,
'w+'
)
as
t_f
:
t_f
.
writelines
(
'study hard and make progress'
)
# 方式二:生成自定義臨時文件(指定前綴、后綴、目錄、文件類型參數,可指定其中一部分),suffix:后綴, prefix:前綴, dir:目錄, text:文件類型,True為文本,false為二進制
tmpfile
=
tempfile
.
mkstemp
(
suffix
=
'.txt'
,
prefix
=
'tp_'
,
dir
=
'/home/china/tmp/py_rs_file'
,
text
=
True
)
[
1
]
print
(
tempfile
)
# /home/china/tmp/py_rs_file/tp_pn2973g0.txt
# 數據寫入
with
open
(
tmpfile
,
'w+'
)
as
t_f
:
t_f
.
writelines
(
'study hard and make progress'
)
3.2 生成自動刪除的臨時文件
# 方式一:創建臨時文件,文件關閉時自動刪除
tmpfile
=
tempfile
.
TemporaryFile
(
mode
=
'w+t'
)
tmpfile
.
write
(
'study hard and make progress everyday'
)
#數據寫入
tmpfile
.
seek
(
0
)
tmpTxt
=
tmpfile
.
read
(
)
#數據讀取
print
(
tmpTxt
)
tmpfile
.
close
(
)
#關閉時文件自動刪除
# 方式二:創建臨時文件,文件關閉時根據delete參數確定是否自動刪除, True:刪除 False:不刪除
with
tempfile
.
NamedTemporaryFile
(
delete
=
False
)
as
tmpfile
:
file_name
=
tmpfile
.
name
print
(
file_name
)
#/tmp/tmp73zl8gmn
tmpfile
.
write
(
'study hard and make progress everyday'
.
encode
(
)
)
tmpfile
.
seek
(
0
)
tmpTxt
=
tmpfile
.
read
(
)
.
decode
(
)
print
(
tmpTxt
)
# 方式三:創建自定義臨時文件,文件關閉時可根據delete參數確定是否自動刪除, True:刪除 False:不刪除
# 其他配置參數有,mode:文件模式(w+b為二進制模式(默認),w+t為文本模式),suffix:后綴, prefix:前綴, dir:目錄
with
tempfile
.
NamedTemporaryFile
(
mode
=
'w+t'
,
suffix
=
'.txt'
,
prefix
=
'tp_'
,
dir
=
'/home/china/tmp/py_rs_file'
,
delete
=
False
)
as
tmpfile
:
file_name
=
tmpfile
.
name
print
(
file_name
)
#/home/china/tmp/py_rs_file/tp_fcwpmh3l.txt
tmpfile
.
write
(
'study hard and make progress everyday'
)
tmpfile
.
seek
(
0
)
tmpTxt
=
tmpfile
.
read
(
)
print
(
tmpTxt
)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
