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(mode='w+t') as file:
# Writing text data into the file
file.write('Hello Geeks!')
# Specifying the position to start reading
file.seek(0)
# Reading the content
print(file.read())
# Closing the file
file.close()
在上面的代码中,我们使用with语句创建了一个临时文件,然后以文本模式( 'w+t') 打开它,并做了与我们在 Python 中处理其他文件相同的所有操作。
Hello Geeks!
命名的临时文件
为了更好地控制制作临时文件,比如根据需要命名临时文件或保留或删除它,那么我们可以使用NamedTemporaryFile().
在创建临时文件的时候,我们可以指定一个后缀和一个前缀,我们可以选择是删除还是保留这个临时文件。它有一个delete参数,默认为True,这意味着当我们关闭它时,该文件将被自动删除,但我们可以将此值更改为以False保留它。
import tempfile
# Creating a temporary file using NamedTemporaryFile()
named_file = tempfile.NamedTemporaryFile()
print('Named file:', named_file)
print('Named file name:', named_file.name)
# Closing the file
named_file.close()
----------
Named file: <tempfile._TemporaryFileWrapper object at 0x000001E70CDEC310>
Named file name: C:\Users\SACHIN\AppData\Local\Temp\tmpk6ycz_ek
上面代码的输出与我们使用该函数创建临时文件时的输出相同TemporaryFile(),这是因为NamedTemporaryFile()操作完全相同TemporaryFile()但是使用创建的临时文件NamedTemporaryFile()保证在文件系统中具有可见的名称。
如何自定义临时文件的名称?
如您所见,我们的临时文件的名称是随机生成的,但我们可以借助prefix和suffix参数更改它。
import tempfile
# Creating a temporary file using NamedTemporaryFile()
named_file = tempfile.NamedTemporaryFile(
prefix='geek-',
suffix='-python'
)
print('Named file name:', named_file.name)
# Closing the file
named_file.close()
现在将在运行代码时创建临时文件,其名称将以我们在上面代码中指定的值作为前缀和后缀。
Named file name: C:\Users\SACHIN\AppData\Local\Temp\geek-n6luwuwx-python
创建临时目录
要创建临时目录,我们可以使用TemporaryDirectory()tempfile 模块中的函数。
import tempfile
# Creating a temporary directory inside the TempDir
tempdir = tempfile.TemporaryDirectory(
dir='TempDir'
)
# Printing the name of temporary dir
print('Temp Directory:', tempdir.name)
# Cleaning up the dir
tempdir.cleanup()
上面的代码将在我们在根目录中创建的**TempDir目录中创建一个临时目录。 **然后我们打印临时目录的名称,然后调用cleanup()显式清理临时目录的方法。
Temp Directory: TempDir\tmplfu2ooew
我们可以使用with语句创建一个临时目录,我们也可以指定suffix和prefix参数。
with tempfile.TemporaryDirectory(
dir='TempDir',
prefix='hey-',
suffix='-there'
) as tempdir:
print("Temp Dir:", tempdir)
当我们使用语句创建临时目录时,with目录的名称将分配给子句的目标as。要获取临时目录的名称,我们通过tempdir而不是tempdir.name在打印语句中。
Temp Dir: TempDir\hey-q14i1hc4-there
你会注意到这次我们没有使用该cleanup()方法,那是因为在临时目录对象的上下文完成后临时目录及其内容被删除。
假脱机临时文件
该SpooledTemporaryFile()函数与 相同TemporaryFile(),不同之处在于它将数据存储在内存中,直到达到最大大小或fileno()调用方法。
import tempfile
# Creating a temporary file to spool data into it
sp_file = tempfile.SpooledTemporaryFile(max_size=10)
print(sp_file)
# Writing into the file
sp_file.write(b'Hello from GeekPython')
# Printing the size of the file
print(sp_file.__sizeof__())
# Printing if data is written to the disk
print(sp_file._rolled)
print(sp_file._file)
将max_size参数设置为10后,我们使用该SpooledTemporaryFile()函数创建一个假脱机临时文件。它表示在滚动到磁盘文件之前,最多可以将 10 个文件存储在内存中。
然后我们将一些数据写入文件并使用属性打印文件的大小__sizeof__。
有一种rollover()方法可以查看数据是在内存中还是滚动到磁盘上的临时文件中。此方法返回一个布尔值,True表示数据已滚动,False表示数据仍在假脱机临时文件的内存中。
<tempfile.SpooledTemporaryFile object at 0x0000023FFBD0C370>
32
True
<tempfile._TemporaryFileWrapper object at 0x0000023FFBD0D930>
可以看出,临时文件对象是SpooledTemporaryFile 。 因为我们写入文件的数据量超过了允许的大小,所以数据被翻转了,我们收到了布尔值True。
根据我们指定的模式,此函数返回一个类文件对象,其_file属性为 anio.BytesIO或 an io.TextIOWrapper(二进制或文本)。io.BytesIO直到数据超过最大大小,此函数使用or缓冲区将数据保存在内存中io.TextIOWrapper。
import tempfile
with tempfile.SpooledTemporaryFile(mode="w+t", max_size=50) as sp_file:
print(sp_file)
# Running a while loop until the data gets rolled over
while sp_file._rolled == False:
sp_file.write("Welcome to GeekPython")
print(sp_file._rolled, sp_file._file)
输出
<tempfile.SpooledTemporaryFile object at 0x000001A8901CC370>
False <_io.TextIOWrapper encoding='cp1252'>
False <_io.TextIOWrapper encoding='cp1252'>
True <tempfile._TemporaryFileWrapper object at 0x000001A8906388E0>
直到数据滚完,我们跑了一个while循环,打印了对象_file的属性SpooledTemporaryFile。正如我们所见,数据是使用缓冲区存储在内存中的io.TextIOWrapper(模式设置为文本),当数据滚动时,代码返回临时文件对象。
我们可以对二进制格式的数据做同样的事情。
import tempfile
with tempfile.SpooledTemporaryFile(mode="w+b", max_size=50) as sp_file:
print(sp_file)
# Running a while loop until the data gets rolled over
while sp_file._rolled == False:
sp_file.write(b"Welcome to GeekPython")
print(sp_file._rolled, sp_file._file)
输出
<tempfile.SpooledTemporaryFile object at 0x00000223C633C370>
False <_io.BytesIO object at 0x00000223C6331580>
False <_io.BytesIO object at 0x00000223C6331580>
True <tempfile._TemporaryFileWrapper object at 0x00000223C67A8850>
我们也可以调用fileno()翻转文件内容。
import tempfile
with tempfile.SpooledTemporaryFile(mode="w+b", max_size=500) as sp_file:
print(sp_file)
for _ in range(3):
sp_file.write(b'Hey, there welcome')
print(sp_file._rolled, sp_file._file)
print('Data is written to the disk before reaching the max size.')
# Calling the fileno() method
sp_file.fileno()
print(sp_file._rolled, sp_file._file)
输出
<tempfile.SpooledTemporaryFile object at 0x000001F51D12C370>
False <_io.BytesIO object at 0x000001F51D121580>
False <_io.BytesIO object at 0x000001F51D121580>
False <_io.BytesIO object at 0x000001F51D121580>
Data is written to the disk before reaching the max size.
True <tempfile._TemporaryFileWrapper object at 0x000001F51D5A0970>
简单功能
tempfile 模块中包含一些低级函数。我们将一一探讨。
mkstemp 和 mkdtemp
mkstemp用于以最安全的方式创建临时文件,mkdtemp用于以最安全的方式创建临时目录。
它们也有类似 , 的参数suffix,prefix但dir还有mkstemp一个text默认为False(二进制模式)的附加参数,如果我们设置它,True则文件将以文本模式打开。
import tempfile
# Using mkstemp
file = tempfile.mkstemp(prefix='hello-', suffix='-world')
print('Created File:', file)
# Using mkdtemp
directory = tempfile.mkdtemp(dir='TempDir')
print('Directory Created:', directory)
----------
Created File: (3, 'C:\Users\SACHIN\AppData\Local\Temp\hello-xmtqn88f-world')
Directory Created: TempDir\tmp_6coyqq2
注意:有一个函数mktemp()也被弃用了。
gettempdir和gettempdirb
gettempdir()用于返回用于临时文件的目录的名称,gettempdirb()也返回目录的名称,但以字节为单位。
import tempfile
print(tempfile.gettempdir())
print(tempfile.gettempdirb())
----------
C:\Users\SACHIN\AppData\Local\Temp
b'C:\Users\SACHIN\AppData\Local\Temp'
结论
本文介绍了 tempfile 模块,它提供创建临时文件和目录的功能 。 我们在代码示例中使用了 tempfile 模块中的各种函数,这有助于我们更好地理解这些函数的运行方式。