Python临时文件Tempfile模块
Python临时文件
在每种编程语言中,程序通常都需要通过创建临时目录和文件来将临时数据存储到文件系统中。
此数据可能尚未完全准备好输出,但是访问这些数据可能会牺牲程序的安全性。
编写仅用于管理临时数据的完整代码也是一个繁琐的过程。
这是因为我们需要编写有关为这些文件和目录创建随机名称,然后对其进行写入的逻辑,一旦完成所有操作,便删除数据。
使用Python中的tempfile
模块,所有这些步骤都变得非常容易。
tempfile模块提供了简单的功能,通过它们我们可以创建临时文件和目录并轻松访问它们。
让我们在这里看到这个模块的运行情况。
创建临时文件
当我们需要创建一个临时文件来存储数据时,我们需要TemporaryFile()
函数。
此功能提供给我们的好处是,在制作新文件时,平台文件系统中没有对该文件的引用,因此,其他程序无法访问这些文件。
这是一个示例程序,它创建一个临时文件并在" TemporaryFile"关闭时清理该文件:
import os import tempfile # Using PID in filename filename = '/tmp/theitroad.%s.txt' % os.getpid() # File mode is read & write temp = open(filename, 'w+b') try: print('temp: {0}'.format(temp)) print('temp.name: {0}'.format(temp.name)) finally: temp.close() # Clean up the temporary file yourself os.remove(filename) print('TemporaryFile:') temp = tempfile.TemporaryFile() try: print('temp: {0}'.format(temp)) print('temp.name: {0}'.format(temp.name)) finally: # Automatically cleans up the file temp.close()
我们来看一下该程序的输出:创建临时文件
在第一个代码段中,我们自己清理文件。
在下一个代码段中,一旦" TemporaryFile"关闭,该文件也会从系统中完全删除。
运行该程序后,您将看到计算机文件系统中不存在任何文件。
从临时文件读取
幸运的是,从临时文件中读取所有数据仅是单个函数调用的问题。
这样,我们可以读取写入文件中的数据,而无需逐字节处理数据或者执行复杂的IO操作。
让我们看一个示例代码片段来演示这一点:
import os import tempfile temp_file = tempfile.TemporaryFile() try: print('Writing data:') temp_file.write(b'This is temporary data.') temp_file.seek(0) print('Reading data: \n\t{0}'.format(temp_file.read())) finally: temp_file.close()
我们只需要在TemporaryFile()对象上调用read()函数,就可以从临时文件中获取所有数据。
最后,请注意,我们仅向该文件写入了字节数据。
在下一个示例中,我们将向其中写入纯文本数据。
将纯文本写入临时文件
在我们编写的最后一个程序中稍作修改,我们也可以将简单的文本数据写入临时文件中:
import tempfile file_mode = 'w+t' with tempfile.TemporaryFile(mode=file_mode) as file: file.writelines(['Java\n', 'Python\n']) file.seek(0) for line in file: print(line.rstrip())
创建命名临时文件
命名临时文件非常重要,因为可能存在跨越多个进程甚至机器的脚本和应用程序。
如果我们命名一个临时文件,则很容易在应用程序的各个部分之间传递它。
让我们看一个使用NamedTemporaryFile()
函数创建一个Named Temporary文件的代码片段:
import os import tempfile temp_file = tempfile.NamedTemporaryFile() try: print('temp_file : {0}'.format(temp_file)) print('temp.temp_file : {0}'.format(temp_file.name)) finally: # Automatically deletes the file temp_file.close() print('Does exists? : {0}'.format(os.path.exists(temp_file.name)))
提供文件名后缀和前缀
有时,我们需要在文件名中包含一些前缀和后缀,以识别文件实现的目的。
这样,我们可以创建多个文件,以便可以在一堆文件中轻松识别出哪些文件可以达到特定目的。
这是一个示例程序,在文件名中提供了前缀和后缀:
import tempfile temp_file = tempfile.NamedTemporaryFile(suffix='_temp', prefix='jd_', dir='/tmp',) try: print('temp:', temp_file) print('temp.name:', temp_file.name) finally: temp_file.close()