阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

教你如何用tempfile库创建python进程中的临时文件

32次阅读
没有评论

共计 2045 个字符,预计需要花费 6 分钟才能阅读完成。

导读 这篇文章主要介绍了如何用 tempfile 库创建 python 进程中的临时文件,帮助大家更好的理解和使用 python,感兴趣的朋友可以了解下
技术背景

临时文件在 python 项目中时常会被使用到,其作用在于随机化的创建不重名的文件,路径一般都是放在 Linux 系统下的 /tmp 目录。如果项目中并不需要持久化的存储一个文件,就可以采用临时文件的形式进行存储和读取,在使用之后可以自行决定是删除还是保留。

tempfile 库的使用

tempfile 一般是 python 内置的一个函数库,不需要单独安装,这里我们直接介绍一下其常规使用方法:

# 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)

上述代码执行的任务为:使用 tempfile.NamedTemporaryFile 创建一个临时文件,其文件名采用的是随机化的字符串格式,作为 name 这样的一个属性来调用。通过执行这个任务,我们可以查看一般是生成什么样格式的临时文件:

[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 代码的执行过程中,产生了 tmppetcksa8 这样的一个文件,我们可以向这个文件中直接 write 一些字符串。这个临时文件被存储在 tmp 目录下,与当前的执行路径无关。同时执行结束之后我们发现,产生的这个临时文件被删除了,这是 NamedTemporaryFile 自带的一个 delete 的属性,默认配置是关闭临时文件后直接删除。

持久化保存临时文件

需要持久化保存临时文件是非常容易的,只需要将上述章节中的 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 文件被持久化的保存在系统中的 /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!
总结概要

本文主要介绍了 python 中自带的 tempfile 库对临时文件的操作,通过 tempfile 库我们可以创建自动删除的或者持久化存储的临时文件,存储路径为 Linux 系统下的 /tmp 目录,而我们还可以根据不同的场景需要对产生的临时文件的后缀进行配置。

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计2045字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中