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