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 yourselfos.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 filetemp.close()

Let’s see the output for this program:

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

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 tempfiletemp_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

读取临时文件

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 tempfilefile_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

将纯文本写入临时文件

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 tempfiletemp_file = tempfile.NamedTemporaryFile()
try:print('temp_file : {0}'.format(temp_file))print('temp.temp_file : {0}'.format(temp_file.name))
finally:# Automatically deletes the filetemp_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

创建命名的临时文件

提供文件名后缀和前缀 (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 tempfiletemp_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

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

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)

Download all Python scripts for this lesson下载本课程的所有Python脚本

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

python模块 包 文件

python模块 包 文件_Python临时文件模块相关推荐

  1. python os模块打开文件_python OS 模块 文件目录操作

    os模块中包含了一系列文件操作的函数,这里介绍的是一些在Linux平台上应用的文件操作函数.由于Linux是C写的,低层的libc库和系统调用的接口都是C API,而Python的os模块中包括了对这 ...

  2. python 逐行读取文件_Python fileinput模块:逐行读取多个文件

    前面章节中,我们学会了使用 open() 和 read()(或者 readline().readlines() )组合,来读取单个文件中的数据.但在某些场景中,可能需要读取多个文件的数据,这种情况下, ...

  3. 【Python】写文件个性化设置模块Python_Xlwt练习

    python:写文件个性化设置模块Python_Xlwt练习 # -*- coding: utf-8 -*- """ Created on Sun Aug 5 22:52 ...

  4. python编程头文件_python头文件怎么写

    本文主要以python2为例.首先介绍一下Python头文件的编程风格,然后再给大家详细介绍import部分的基本用法.这两个部分就是Python中头文件的组成模块. 编程风格#!/usr/bin/e ...

  5. python编程头文件_python头文件的编程风格

    python头文件的编程风格 发布时间:2020-09-03 10:23:25 来源:亿速云 阅读:96 作者:小新 小编给大家分享一下python头文件的编程风格,希望大家阅读完这篇文章后大所收获, ...

  6. python常用包下载_Python及其常用模块库下载及安装

    一.Python下载: https://www.python.org/downloads/ 二.Python模块下载: http://www.lfd.uci.edu/~gohlke/pythonlib ...

  7. python导入自定义文件_python引入导入自定义模块和外部文件的实例

    项目中想使用以前的代码,或者什么样的需求致使你需要导入外部的包 如果是web 下,比如说django ,那么你新建一个app,把你需要导入的说用东东,都写到这个app中,然后在setting中的app ...

  8. python 导入包 作用域_Python 包、模块、函数、变量作用域

    Python 项目的组织结构 - 包 -- 模块 --- 类 ---- 函数.变量 Python是利用包和模块来组织一个项目的. 包: 包的物理表现是一个文件夹,但是一个文件夹却不一定是个包,要想让个 ...

  9. python tempfile自动删除_Python tempfile模块生成临时文件和临时目录

    tempfile 模块专门用于创建临时文件和临时目录,它既可以在 UNIX 平台上运行良好,也可以在 Windows 平台上运行良好. tempfile 模块中常用的函数,如表 1 所示. 表 1 t ...

最新文章

  1. 在Linux系统安装Node.js
  2. linux7设置时间,CentOS 7 设置日期和时间
  3. lightgbm过去版本安装包_云顶手游10.13安装包,6月24日
  4. 解决Visual Code安装中文插件失败问题
  5. 模板类中使用友元函数的方式,派生类友元函数对基类的成员使用情况
  6. mysql使用DISTINCT进行去重
  7. Android Studio显示行数
  8. 本周开课 | 第 5 期全基因组/外显子组家系分析理论和实战
  9. 分享一个绝佳的实战机器学习的机会,边学边比拿奖金!
  10. ubuntu中mysql怎么退出命令_ubuntu的Linux下安装MySQL
  11. java实现调查问卷_智能办公进行时丨富士施乐邀您参与有奖问卷调查
  12. package的创建安装和使用
  13. PAT (Basic Level) Practice1009 说反话
  14. HTML中标签的ref属性,itemref(属性) | itemref (attribute)
  15. 教程:游戏LOGO=游戏符号+名字
  16. win10彻底关闭休眠状态(1909以上版本)
  17. 超详细Docker部署SpringBoot+Vue项目(三更博客项目部署)
  18. 7-1 统计正数和负数的个数然后计算这些数的平均值 (15 分)-java
  19. uni-app小说阅读页,vue小说阅读页,静态demo
  20. 谍影重重3在线观看,谍影重重3剧情介绍

热门文章

  1. DataTable判断列是否为空!(实用)
  2. document.addEventListener的使用介绍
  3. 点4下还是点1下?使用jQuery启动一个SharePoint工作流
  4. [转载] 利用python制作简单计算器
  5. [转载] python+opencv图像处理:numpy数组操作
  6. [转载] python学习笔记(三)- numpy基础:array及matrix详解
  7. [转载] Python|range函数用法完全解读
  8. vivado中FIFO IP核的Standard FIFO和First-word-Fall-Through模式的仿真比较
  9. NOIP2017 Day1 T1 小凯的疑惑
  10. Oracle redo 日志切换时间频率