技术背景
临时文件在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目录,而我们还可以根据不同的场景需要对产生的临时文件的后缀进行配置。
原文链接为:https://www.cnblogs.com/dechinphy/p/tempfile.html
以上就是如何用tempfile库创建python进程中的临时文件的详细内容,更多关于tempfile库创建临时文件的资料请关注其它相关文章!
更新日志
- 群星2013-青春缤纷辑压箱宝大公开3CD2[新加坡限量版][WAV整轨]
- 林育群.2013-BalladShow(日本版)【环球】【WAV+CUE】
- 陈加洛.1992-痛到感觉不到【宝丽金】【WAV+CUE】
- 群星.2023-宿命之敌电视剧原声带【韶愔音乐】【FLAC分轨】
- 東京事変-大発見[FLAC+CUE]
- 椎名林檎-三文ゴシップ[FLAC+CUE]
- 2024年08月04日
- 裘德《裘德「最后的水族馆」演唱会LIVE》[320K/MP3][228.89MB]
- 裘德《裘德「最后的水族馆」演唱会LIVE》[24bit 48kHz][FLAC/分轨][2.08G]
- 基因三重奏《如果你什么都不说 音乐会现场录音》[320K/MP3][145.37MB]
- 孟庭苇.1996-月亮说话(2020环球24KGOLD限量版)【上华】【WAV+CUE】
- 群星.1997-新艺宝优质音响系列·国语精选监听版【新艺宝】【WAV+CUE】
- 阿桑.2005-寂寞在唱歌(星外星引进版)【华研国际】【WAV+CUE】
- 基因三重奏《如果你什么都不说 音乐会现场录音》[FLAC/分轨][287.43MB]
- 蔡题谦《我爱你,却依然要看你走》[320K/MP3][88.65MB]