前面钢铁老豆给大家介绍了Python是如何进行文件、目录和路径相关操作的。
今天,延续这个话题,我们来讲讲临时文件、目录的创建和删除,尤其适用于那些需要临时存储数据但不想把数据永久保存到硬盘上的场合,这就像是Python给你的一个隐形的小盒子,你可以随时向里面丢东西,用完后盒子就自动消失不见了。
所以主角就是Python的内置模块:tempfile。
0.tempfile模块介绍
tempfile模块提供了一系列创建临时文件和目录的方法。这些临时文件和目录在用完后可以被轻松删除,这样就不会留下垃圾数据,维护系统的干净整洁。
1.快速用法
钢铁老豆,习惯按文件或目录、退出是否自动删除,分成4种情况:
1.1 创建临时文件 + 自动删除 (对象关闭或程序退出时)
import tempfile
# with tempfile.TemporaryFile() as temp: # 文件系统中不可见 (非隐藏文件)
# with tempfile.SpooledTemporaryFile(max_size=1000) as temp: # 文件系统中不可见 (非隐藏文件),超过大小阈值(如1000字节)后,将从内存转存至磁盘,后续读写全部基于磁盘,不再回到内存
with tempfile.NamedTemporaryFile() as temp: # 文件系统中可见
print(temp)
print(temp.name) # 对于TemporaryFile、SpooledTemporaryFile没有实际意义
temp.write(b'Hello World!')
temp.seek(0) # 将文件指针重新定位到文件开头
print(temp.read())
# temp.close()
1.2 创建临时目录 + 自动删除 (对象关闭或程序退出时)
import tempfile
with tempfile.TemporaryDirectory() as tempdir:
print(tempdir)
# tempdir.cleanup()
1.3 创建临时文件 + 不自动删除 (对象关闭或程序退出时)
import tempfile
import os
fd, path = tempfile.mkstemp()
try:
with os.fdopen(fd, 'w') as tmp:
tmp.write('Hello world!')
finally:
os.remove(path)
1.4 创建临时目录 + 不自动删除 (对象关闭或程序退出时)
import tempfile
import shutil
path = tempfile.mkdtemp()
try:
print('temp dir:', path)
finally:
shutil.rmtree(path)
上面这4种情况,都可以通过参数指定前缀、后缀和保存目录
- prefix:临时文件或目录的前缀
- suffix:临时文件或目录的后缀
- dir:临时文件/目录的保存目录,注意保存目录必须存在,且有相应权限
import tempfile
# 创建一个有指定前缀和后缀的临时文件,该文件在指定的目录下
with tempfile.NamedTemporaryFile(prefix="pre_", suffix="_suf", dir=".") as temp:
print(temp.name)
# 创建一个有指定前缀的临时目录,该目录在指定的位置下
with tempfile.TemporaryDirectory(prefix="pre_", suffix='_suf', dir=".") as tempdir:
print(tempdir)
好了,以上就是今天的内容,希望能帮你解决在Python项目中处理临时文件和目录的需求。如果你有什么问题或者想要了解更多关于Python的知识,记得留言讨论哦。
欢迎点赞+收藏+评论+关注,每天学习一点Python小知识,无论基础、模块、数据分析、深度学习和AI,总有你感兴趣的。我是钢铁老豆,一个30岁转行IT、自学成为算法工程师、想用Ai点亮孩子小小世界的Pythoner。