在Python中创建临时文件
本文解释了如何在Python中创建一个临时文件和目录。Python 中的临时文件是用tempfile
模块生成的。
本文还解释了tempfile
的四个子函数,即TemporaryFile
,NamedTemporaryFile
,mkstemp
, 和TemporaryDirectory
。
使用tempfile
模块在 Python 中创建临时文件
这个函数在Python中创建一个安全的临时文件,它返回一个类似于文件的存储区域,可以临时利用。一旦它被关闭,就会被销毁 (包括对象被垃圾回收时的隐式关闭)。
使用这个函数在Python中创建一个临时文件的语法是 :
file = tempfile.TemporaryFile()
# OR
file = tempfile.TemporaryFile(mode='w+b', #Remains as Default mode if not mentioned
suffix=None, #adds a suffix to file name
prefix=None, #adds prefix to file name
# etc.)
在Python中,这个临时文件将在上下文完成 (with
block) 或文件对象销毁时从文件系统中删除file.close()
。由于模式参数的默认值是w+b
,新文件可以被读写而不被关闭。
它在二进制模式下运行,以保持所有系统的一致性,无论保存的数据如何。一些额外的术语,如缓冲、编码、错误和换行,是python内置函数open()
的一部分,可以在参数内使用。
下面的程序演示了如何使用TemporaryFile()
,在Python中创建一个临时文件。
第一行代码导入库包tmpfile
。创建了一个变量filepath
,使用tempfile.TemporaryFile()
函数来创建一个临时文件。
使用filepath.write()
函数在临时文件中写入数据。这个参数只接受一个字节类型的值,所以在字符串前添加了字面意思b
。
filepath.seek(0)
函数在文件流中从长度0开始加载文件。
打印变量filepath
,显示对象的地址。为了检查临时文件的文件名,打印函数filepath.name()
。
函数filepath.read()
从临时文件中读取数据,然后被打印。最后,使用filepath.close()
释放临时文件对象。
import tempfile
filepath = tempfile.TemporaryFile()
filepath.write(b'Writing some stuff')
filepath.seek(0)
print(filepath)
print(filepath.name)
print(filepath.read())
filepath.close()
输出:
"C:UsersWin 10venvScriptspython.exe" "C:/Users/Win 10/main.py"
<tempfile._TemporaryFileWrapper object at 0x00000285D92DAC50>
C:UsersWIN10~1AppDataLocalTempst.cq3d03ezloraine
b'Hello world!'
Process finished with exit code 0
让我们来看看另一个程序。
这里的变量filepath
使用了TemporaryFile
子函数的三个参数。模式被设置为w+b
,它代表读写。
同时,在文件名中加入前缀st.
和后缀loarine
。数据被写入临时文件中,文件名被打印出来。
import tempfile
filepath = tempfile.TemporaryFile(mode='w+b',
prefix='st.', # adds prefix to file name
suffix='loraine', # adds a suffix to file name
)
filepath.write(b'Hello world!')
print(filepath.name)
filepath.close()
可以看出,前缀和后缀已经被添加到文件名中。
"C:UsersWin 10venvScriptspython.exe" "C:/Users/Win 10/main.py"
C:UsersWIN10~1AppDataLocalTempst.kepthvu_loraine
Process finished with exit code 0
可以看出,临时文件在程序结束时已被明确关闭。这样做关闭了文件,但并没有删除它。
即使在关闭文件后,也可以显示文件名,但其内容不能被加载。
在 Python 中读或写一个关闭的临时文件的结果是 Value Error,与任何正常的文件相同。
import tempfile
filepath = tempfile.TemporaryFile(mode='w+b',
prefix='st.', # adds prefix to file name
suffix='loraine', # adds a suffix to file name
)
filepath.write(b'Hello world!')
filepath.close()
print(filepath.name)
filepath.write(b'Hello world!')
输出:
"C:UsersWin 10venvScriptspython.exe" "C:/Users/Win 10/main.py"
C:UsersWIN10~1AppDataLocalTempst.f7n0s5a6loraine
Traceback (most recent call last):
File "C:/Users/Win 10/main.py", line 14, in <module>
filepath.write(b'Hello world!')
File "C:Python36libtempfile.py", line 485, in func_wrapper
return func(*args, **kwargs)
ValueError: write to closed file
Process finished with exit code 1
在 Python 中创建一个命名的临时文件
这个函数和TemporaryFile()
的唯一区别是,这个函数确保文件在文件系统中有一个可见的名字。这个名字可以在返回对象时在name
属性中找到。
在 UNIX 中,即使前一个文件已经打开,同一个名字也可以用来打开另一个临时文件,但在 Windows 中是禁止的。
默认情况下,Python 中的临时文件被设置为一旦关闭就立即删除,但是可以通过设置delete = False
来关闭它。与普通文件类似,这个类似文件的对象可以在语句中使用。
使用这个子函数的语法是:
tmp = tempfile.NamedTemporaryFile()
# OR
tmp = tempfile.NamedTemporaryFile(mode='w+b',
delete=False,
suffix=None,
prefix=None)
要在Python中创建一个命名的临时文件,使用下面的程序。
这个程序在这里导入了两个库包,os
和tempfile
。使用变量tempo_file
创建一个临时文件,delete
参数被设置为False
,并提供了一个前缀和后缀。
在try
块内,使用print(tempo_file)
打印文件对象。然后,使用print(tempo_file.name)
打印文件名。
函数tempo_file.write()
被用来在这个临时文件内写入。
在finally
块内,使用tempo_file.close()
关闭文件。然后使用函数os.unlink()
,将文件名从文件对象中取消链接。
import os
import tempfile
tempo_file = tempfile.NamedTemporaryFile(delete=False, prefix="Ice", suffix='cream')
try:
print(tempo_file)
print(tempo_file.name)
tempo_file.write(b'Peacock is national bird of India')
finally:
tempo_file.close()
os.unlink(tempo_file.name)
输出:
"C:UsersWin 10venvScriptspython.exe" "C:/Users/Win 10/main.py"
<tempfile._TemporaryFileWrapper object at 0x000001DE90935C18>
C:UsersWIN10~1AppDataLocalTempIcez5eghui0cream
Process finished with exit code 0
在上面的程序中,delete
参数变成了False
,这意味着如果它没有被隐式关闭,它仍然是开放的。如果delete
参数被设置为True
,那么在文件被关闭后就不能访问文件名。
import os
import tempfile
tempo_file = tempfile.NamedTemporaryFile(delete=True)
try:
print(tempo_file.name)
finally:
tempo_file.close()
os.unlink(tempo_file.name)
print(tempo_file.name)
输出:
"C:UsersWin 10venvScriptspython.exe" "C:/Users/Win 10/ain.py"
C:UsersWIN10~1AppDataLocalTemptmp6j3xxjzr
Traceback (most recent call last):
File "C:/Users/Win 10/main.py", line 14, in <module>
os.unlink(tempo_file.name)
FileNotFoundError: [WinError 2] The system cannot find the file specified:'C:\Users\WIN10~1\AppData\Local\Temp\tmp6j3xxjzr'
Process finished with exit code 1
一个with
块是有帮助的,因为它自动关闭了文件。
import tempfile
with tempfile.TemporaryFile(delete=True) as tempo_file:
print(tempo_file)
print(tempo_file.name)
tempo_file.write(b'Peacock is national bird of India')
print(tempo_file.read())
输出:
"C:UsersWin 10venvScriptspython.exe" "C:/Users/Win 10/main.py"
<tempfile._TemporaryFileWrapper object at 0x0000027EB1C09390>
C:UsersWIN10~1AppDataLocalTemptmpzk_gpkau
Traceback (most recent call last):
File "C:/Users/Win 10/main.py", line 11, in <module>
print(tempo_file.read())
File "C:Python36libtempfile.py", line 485, in func_wrapper
return func(*args, **kwargs)
ValueError: read of closed file
Process finished with exit code 1
使用mkstemp
函数在Python中创建临时文件
这个函数提供了在Python中创建临时文件的最高安全级别。只有创建该文件的用户ID才有权限读取和写入该文件。
如果平台采用权限位来确定一个文件是否可执行,则没有人可以执行该文件。即使是子进程也不能继承文件描述符。
用于mkstemp
的语法是:
tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)
与函数TemporaryFile()
不同,在使用mkstemp()
时,程序员必须隐含地删除临时文件。该函数对prefix
、suffix
和dir
参数有独特的作用。
让我们来看看它们。
如果没有设置为None
,文件名将以给定的后缀结尾;否则,不会有后缀。如果需要的话,必须在后缀的开头加上一个点,因为mkstemp()
,在文件名和后缀之间不加点。
如果有前缀,文件名将以前缀开始,而不是None
;否则,将使用一个默认的前缀。从gettempprefix()
或gettempprefixb()
返回的值作为默认值,无论哪个程序都是合适的。
dir
存储临时文件的目录。如果dir
没有设置为None
,将在给定的目录下创建文件;否则,将使用默认目录。
默认目录是与平台有关的。
通过改变TMPDIR
,TEMP
, 或TMP
环境变量,应用程序用户可以从该平台特定的列表中覆盖默认目录的选择。
suffix
如果没有设置为None
,那么prefix
和dir
必须具有相同的类型。如果这些是字节,返回的名称将是字节而不是str
。
传递suffix=b
将在返回值中强制使用字节而不是其默认行为。
如果指定了文本和True
,文件将以文本模式打开。如果设置为False
,系统默认以二进制模式打开文件。
下面的程序使用mkstemp
创建一个临时文件。mkstemp
函数使用两个参数,第一个参数是文件的标识符,第二个参数是文件名。
在一个try
区块内,通过其句柄使用with
区块打开文件。然后在文件中写入一些数据。
在finally
块内,使用os.unlink(filename)
隐式删除该文件。
import os
import tempfile
handle, filename = tempfile.mkstemp(suffix=".bat")
try:
with os.fdopen(handle, "w") as f:
f.write("signature")
print(handle)
print(filename)
finally:
os.unlink(filename)
输出:
"C:UsersWin 10venvScriptspython.exe" "C:/Users/Win 10/main.py"
3
C:UsersWIN10~1AppDataLocalTemptmp1yvy9j_c.bat
Process finished with exit code 0
在Python中创建一个临时目录
这个类安全地创建了一个临时目录。这些对象可以使用像with
块一样的上下文管理器。
新形成的临时目录和它们的内容在上下文完成或临时目录对象销毁时从内存中删除。
返回的对象的name
属性包含了目录的名称,这个名称可以被获得。with
当返回的对象被用作上下文管理器时,这个名字会被赋予as
子句中的目标(如果有的话)。
比如说:
with tempfile.TemporaryDirectory() as f: # 'f' is the 'as' clause in this while statement
print('Temporary directory is created', f)
调用cleanup()
方法将显式地擦除该目录。如果ignore cleanup errors
为真,任何在显式或隐式清理过程中未处理的异常都将被忽略。
任何剩余的可移动项目都将使用最佳努力技术被销毁。
为了创建一个临时目录,我们可以使用下面的Python程序:
import tempfile
with tempfile.TemporaryDirectory() as f:
print('Temporary directory is created', f)
输出:
"C:UsersWin 10venvScriptspython.exe" "C:/Users/Win 10/main.py"
Temporary directory is created C:UsersWIN10~1AppDataLocalTemptmp1gk3c5z8
Process finished with exit code 0
本文已经解释了使用Python中的tempfile
模块及其子函数来创建临时文件的方法。