Python:使用 tempfile 生成临时文件和目录

本文详细介绍了Python的tempfile模块,包括如何创建、读取和操作临时文件及目录。通过TemporaryFile()、NamedTemporaryFile()和TemporaryDirectory()等函数,展示了如何在程序执行期间使用临时文件存储数据,并在完成后进行清理。文章还讨论了如何自定义临时文件的名称,以及使用SpooledTemporaryFile()处理大量数据。最后,提到了低级功能如mkstemp()和mkdtemp(),以及获取临时目录名称的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 拥有丰富的标准库集合来执行各种任务。在 Python 中,有一个名为tempfile 的模块允许我们创建和操作临时文件和目录。

我们可以使用tempfile创建临时文件和目录,用于在程序执行过程中存放临时数据。该模块具有允许我们创建、读取和操作临时文件和目录的功能。

在本文中,我们将回顾 tempfile 模块的基础知识,包括创建、读取和操作临时文件和目录,以及在我们完成它们后的清理。

创建临时文件
tempfile 模块包含一个名为的函数TemporaryFile(),它允许我们创建一个临时文件用作临时存储。只需输入以下代码即可创建一个临时文件。

import tempfile

# Creating a temporary file
temp_file = tempfile.TemporaryFile()

print(f'Tempfile object: {temp_file}')
print(f'Tempfile name: {temp_file.name}')

# Closing the file 
temp_file.close()

首先,我们导入了模块,因为它是标准 Python 库的一部分,所以我们不需要安装它。

然后我们使用该TemporaryFile()函数创建一个临时文件,我们将其保存在temp_file变量中。然后我们添加打印语句来显示临时文件对象和临时文件名。

最后,我们使用close()函数关闭文件,就像我们关闭任何其他文件一样。这将自动清理并删除文件。

输出

Tempfile object: <tempfile._TemporaryFileWrapper object at 0x0000015E54545AE0>
Tempfile name: C:\Users\SACHIN\AppData\Local\Temp\tmp5jyjavv2

当我们打印对象时,我们得到了对象在内存中的位置,当我们打印临时文件的名称时,我们得到了带有整个路径的temp_file随机名称。tmp5jyjavv2

我们可以指定dir参数在指定目录下创建一个临时文件。

import tempfile

# Creating a temporary file in the cwd
named_file = tempfile.TemporaryFile(
    dir='./'
)

print('File created in the cwd')
print(named_file.name)

# Closing the file
named_file.close()

该文件将在当前工作目录中创建。

File created in the cwd
D:\SACHIN\Pycharm\tempfile_module\tmptbg9u6wk

编写文本并阅读
该TemporaryFile()函数将模式参数设置’w+b’为默认值,以二进制模式读写文件。我们还可以使用’w+t’模式将文本数据写入临时文件。

import tempfile

# Creating a temporary file
file = tempfile.TemporaryFile()

try:
    # Writing into the temporary file
    file.write(b"Welcome to GeekPython.")
    # Position to start reading the file
    file.seek(0)  # Reading will start from beginning
    # Reading the file
    data = file.read()
    print(data)
finally:
    # Closing the file
    file.close()

----------
b'Welcome to GeekPython.'

在上面的代码中,我们创建了一个临时文件,然后使用函数write()将数据写入其中,以字节格式传递字符串(如’b’内容前的前缀所示)。

然后我们使用该函数读取内容,但首先,我们使用(从头开始)函数read()指定开始读取内容的位置,最后,我们关闭文件。seek(0)

使用上下文管理器
我们还可以使用关键字等上下文管理器创建临时文件with。此外,以下示例将向我们展示如何将文本数据写入和读取到临时文件中。

import tempfile

# Using with statement creating a temporary file
with tempfile.TemporaryFile
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Q shen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值