python模块 包 文件_Python临时文件模块

python模块 包 文件

Python临时文件 (Python Tempfile)

In every programming languages, it’s often that program need to store temporary data into the file system by creating temporary directories and files. This data might not be completely ready for output but still, accessing this data can sacrifice the security layer of a program. Writing complete code for just managing temporary data is a cumbersome process as well. This is because we need to write logic about creating random names for these files and directories and then writing to them followed by deleting the data once all operations are complete.

在每种编程语言中,程序通常都需要通过创建临时目录和文件来将临时数据存储到文件系统中。 该数据可能尚未完全准备好输出,但是访问这些数据可能会牺牲程序的安全性。 编写仅用于管理临时数据的完整代码也是一个繁琐的过程。 这是因为我们需要编写有关为这些文件和目录创建随机名称,然后对其进行写入的逻辑,一旦完成所有操作,便删除数据。

All of these steps are made very easy with tempfile module in Python. The tempfile module provides easy functions through which we can make temporary files and directories and access them easily as well. Let’s see this module in action here.

使用Python中的tempfile模块,所有这些步骤都变得非常容易。 tempfile模块提供了简单的功能,通过这些功能,我们可以创建临时文件和目录并轻松访问它们。 让我们在这里看到该模块的运行情况。

创建临时文件 (Creating Temporary files)

When we need to create a temporary file to store data, TemporaryFile() function is something we want. The advantage this function provides us is that when it makes a new file, there are no references to the file in the platform’s file system and so, it is impossible for other programs to access those files.

当我们需要创建一个临时文件来存储数据时,我们需要TemporaryFile()函数。 此功能提供给我们的好处是,在制作新文件时, 平台文件系统没有对该文件的引用 ,因此其他程序无法访问这些文件。

Here is a sample program which creates a temporary file and cleans up the file when TemporaryFile is closed:

这是一个示例程序,该程序创建一个临时文件并在TemporaryFile关闭时清理该文件:

import os
import tempfile

# Using PID in filename
filename = '/tmp/journaldev.%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()

Let’s see the output for this program:

让我们看一下该程序的输出:

python tempfile example

Creating Temporary file

创建临时文件

In the first code snippet, we clean the file ourself. In the next code snippet, as soon as the TemporaryFile is closed, the file is completely deleted from the system as well.

在第一个代码段中,我们自己清理文件。 在下一个代码片段中,一旦TemporaryFile关闭,该文件也会从系统中完全删除。

Once you run this program, you will see that no files exist in the filesystem of your machine.

运行该程序后,您将看到计算机文件系统中不存在任何文件。

从临时文件读取 (Reading from Temporary file)

Luckily, reading all data from a temporary file is just a matter of single function call. With this, we can read data we write in the file without handling it byte by byte or doing complex IO operations.

幸运的是,从临时文件中读取所有数据只是一个函数调用的问题。 这样,我们可以读取写入文件中的数据,而无需逐字节处理数据或执行复杂的IO操作。

Let’s look at a sample code snippet to demonstrate this:

让我们看一个示例代码片段以演示这一点:

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()

Let’s see the output for this program:

让我们看一下该程序的输出:

Reading a Tempfile in python

Reading a Tempfile

读取临时文件

We only had to call read() function on the TemporaryFile() object and we were able to get all data back from the temporary file. Finally, note that we wrote only byte data to this file. In the next example, we will write plain-text data to it.

我们只需要在TemporaryFile()对象上调用read()函数,就可以从临时文件中获取所有数据。 最后,请注意,我们仅向该文件写入了字节数据。 在下一个示例中,我们将向其中写入纯文本数据。

将纯文本写入临时文件 (Writing Plain-text into Temporary File)

With slight modifications in the last program we write, we can write simple text data into a temporary file as well:

在我们编写的最后一个程序中稍作修改,我们也可以将简单的文本数据写入临时文件中:

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())

Let’s see the output for this program:

让我们看一下该程序的输出:

Writing Plain text into Temporary file

Writing Plain text into Temporary file

将纯文本写入临时文件


We changed the mode of the file to
我们将文件的模式更改为 t, which is important if we want to write textual data into our temporary files. t ,这对于将文本数据写入临时文件非常重要。

创建命名临时文件 (Creating Named Temporary files)

Named Temporary files are important to have because there might be scripts and applications which spans across multiple processes or even machines. If we name a temporary file, it is easy to pass it between the parts of the application.

命名临时文件非常重要,因为可能存在跨越多个进程甚至机器的脚本和应用程序。 如果我们命名一个临时文件,则很容易在应用程序的各个部分之间传递它。

Let’s look at a code snippet which makes use of NamedTemporaryFile() function to create a Named Temporary file:

让我们看一个使用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)))

Let’s see the output for this program:

让我们看一下该程序的输出:

Creating named temporary file

Creating named temporary file

创建命名的临时文件

提供文件名后缀和前缀 (Providing File name Suffix and Prefix)

Sometimes, we need to have some prefix and suffix in the file names to identify a purpose that file fulfils. This way, we can create multiple files so that they are easy to identify in a bunch of files about what file achieves a specific purpose.

有时,我们需要在文件名中包含一些前缀和后缀,以识别文件实现的目的。 这样,我们可以创建多个文件,以便可以在一堆文件中轻松识别出哪些文件可以达到特定目的。

Here is a sample program which provides prefix and suffix into the file names:

这是一个示例程序,在文件名中提供了前缀和后缀:

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()

Let’s see the output for this program:

让我们看一下该程序的输出:

Tempfile with Prefix and Suffix

Tempfile with Prefix and Suffix

带有前缀和后缀的临时文件


We just provided three arguments to the
我们只是为 NamedTemporaryFile() function and it manages providing prefix and suffix to the temporary file this module creates. NamedTemporaryFile()函数提供了三个参数,它管理为该模块创建的临时文件提供前缀和后缀。

结论 (Conclusion)

In this lesson, we studied how we can securely create temporary files for our programs and application. We also saw how we can create files which can span across multiple processes and saw how we can provide a prefix & suffix to fle names so that they easily signify what data they contain.

在本课程中,我们研究了如何安全地为程序和应用程序创建临时文件。 我们还看到了如何创建可以跨多个进程的文件,并看到了如何为文件名提供前缀和后缀,以便它们轻松表示它们包含的数据。

Read more Python posts here.

在此处阅读更多Python帖子。

下载源代码 (Download the Source Code)

翻译自: https://www.journaldev.com/20503/python-tempfile-module

python模块 包 文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值