「Python实用秘技13」Python中临时文件的妙用 - 费弗里
source link: https://www.cnblogs.com/feffery/p/17157404.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
「Python实用秘技13」Python中临时文件的妙用
本文完整示例代码及文件已上传至我的
Github
仓库https://github.com/CNFeffery/PythonPracticalSkills
这是我的系列文章「Python实用秘技」的第13期,本系列立足于笔者日常工作中使用Python
积累的心得体会,每一期为大家带来一个几分钟内就可学会的简单小技巧。
作为系列第13期,我们即将学习的是:Python
中临时文件的妙用。
当我们用Python
编写程序时,有时候需要临时存储数据且不希望占用多少内存,亦或是需要写出文件到文件系统供后续程序读取,这些情况下以创建临时文件的方式进行处理,既不会干扰本地文件系统,又安全省事。
而通过使用Python
中的标准库tempfile
,我们就可以很方便的进行临时文件相关操作,其主要用法有两种:
- 创建临时文件
tempfile
的经典用法之一是使用其TemporaryFile()
配合with
上下文管理器,在本地文件系统的临时文件目录下创建具有随机名称的文件,并且在with
内的代码执行完成后,该临时文件会自动被销毁:
import os
import tempfile
with tempfile.TemporaryFile() as f:
print(f.name)
print(os.path.exists(f.name))
print(os.path.exists(f.name))
基于这个特性,我们可以应用到很多场景下,譬如当我们希望将表格格式的字符串转换为pandas
数据框时,就可以像下面这样做:
- 创建临时目录
前面展示了tempfile
创建临时文件的功能,而有些场景下,我们需要创建临时文件夹,这可以基于TemporaryDirectory()
来实现,特性类似TemporaryFile()
:
典型的应用场景是配合TemporaryDirectory()
和shutil
生成压缩包文件:
import shutil
import zipfile
import numpy as np
with tempfile.TemporaryDirectory() as p:
# 模拟向当前临时目录下写出多个文件
for i in range(100):
(
pd
.DataFrame(np.random.rand(10, 3), columns=list('ABC'))
.to_csv(os.path.join(p, f'demo{i+1}.csv'), index=False)
)
# 将当前临时目录转为zip压缩包
shutil.make_archive('./demo', 'zip', p)
# 查看目标压缩文件内的文件
[file.filename for file in zipfile.ZipFile('demo.zip').filelist]
本期分享结束,咱们下回见~👋
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK