6

「Python实用秘技13」Python中临时文件的妙用 - 费弗里

 1 year ago
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.
neoserver,ios ssh client

「Python实用秘技13」Python中临时文件的妙用

本文完整示例代码及文件已上传至我的Github仓库https://github.com/CNFeffery/PythonPracticalSkills

  这是我的系列文章「Python实用秘技」的第13期,本系列立足于笔者日常工作中使用Python积累的心得体会,每一期为大家带来一个几分钟内就可学会的简单小技巧。

  作为系列第13期,我们即将学习的是:Python中临时文件的妙用。

1344061-20230226192617193-202078330.jpg

  当我们用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))

1344061-20230226192619520-433701745.png

  基于这个特性,我们可以应用到很多场景下,譬如当我们希望将表格格式的字符串转换为pandas数据框时,就可以像下面这样做:

1344061-20230226192621632-1854929989.png
  • 创建临时目录

  前面展示了tempfile创建临时文件的功能,而有些场景下,我们需要创建临时文件夹,这可以基于TemporaryDirectory()来实现,特性类似TemporaryFile()

1344061-20230226192623854-2007683919.png

  典型的应用场景是配合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]

1344061-20230226192625883-400097.png

  本期分享结束,咱们下回见~👋


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK