主要有以下几个函数:

tempfile.TemporaryFile

如何你的应用程序需要一个临时文件来存储数据,但不需要同其他程序共享,那么用TemporaryFile函数创建临时文件是最好的选择。其他的应用程序是无法找到或打开这个文件的,因为它并没有引用文件系统表。用这个函数创建的临时文件,关闭后会自动删除。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os
import tempfile
 
print 'Building a file name yourself:'
filename = '/tmp/guess_my_name.%s.txt' % os.getpid()
temp = open(filename, 'w+b')
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()
    os.remove(filename)     # Clean up the temporary file yourself
 
print
print 'TemporaryFile:'
temp = tempfile.TemporaryFile()
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()  # Automatically cleans up the file

这个例子说明了普通创建文件的方法与TemporaryFile()的不同之处,注意:用TemporaryFile()创建的文件没有文件名

$ python tempfile_TemporaryFile.py

Building a file name yourself:

temp: <open file '/tmp/guess_my_name.14932.txt', mode 'w+b' at 0x1004481e0>

temp.name: /tmp/guess_my_name.14932.txt

TemporaryFile:

temp: <open file '<fdopen>', mode 'w+b' at 0x1004486f0>

temp.name: <fdopen>

默认情况下使用w+b权限创建文件,在任何平台中都是如此,并且程序可以对它进行读写。

1
2
3
4
5
6
7
8
9
10
11
import os
import tempfile
 
temp = tempfile.TemporaryFile()
try:
    temp.write('Some data')
    temp.seek(0)
     
    print temp.read()
finally:
    temp.close()

写入侯,需要使用seek(),为了以后读取数据。

$ python tempfile_TemporaryFile_binary.py

Some data

如果你想让文件以text模式运行,那么在创建的时候要修改mode为'w+t'

1
2
3
4
5
6
7
8
9
10
11
import tempfile
 
f = tempfile.TemporaryFile(mode='w+t')
try:
    f.writelines(['first\n', 'second\n'])
    f.seek(0)
 
    for line in f:
        print line.rstrip()
finally:
    f.close()

$ python tempfile_TemporaryFile_text.py

first

second

tempfile.NamedTemporaryFile

如果临时文件会被多个进程或主机使用,那么建立一个有名字的文件是最简单的方法。这就是NamedTemporaryFile要做的,可以使用name属性访问它的名字

1
2
3
4
5
6
7
8
9
10
11
import os
import tempfile
 
temp = tempfile.NamedTemporaryFile()
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    # Automatically cleans up the file
    temp.close()
print 'Exists after close:', os.path.exists(temp.name)

尽管文件带有名字,但它仍然会在close后自动删除

$ python tempfile_NamedTemporaryFile.py

temp: <open file '<fdopen>', mode 'w+b' at 0x1004481e0>

temp.name: /var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmp0zHZvX

Exists after close: False

tempfile.mkdtemp

创建临时目录,这个不多说,直接看例子

1
2
3
4
5
6
7
import os
import tempfile
 
directory_name = tempfile.mkdtemp()
print directory_name
# Clean up the directory yourself
os.removedirs(directory_name)

$ python tempfile_mkdtemp.py

/var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmpB1CR8M

目录需要手动删除。

Predicting Names

用3个参数来控制文件名,名字产生公式:dir + prefix + random + suffix

1
2
3
4
5
6
7
8
9
10
11
import tempfile
 
temp = tempfile.NamedTemporaryFile(suffix='_suffix',
                                   prefix='prefix_',
                                   dir='/tmp',
                                   )
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close()

$ python tempfile_NamedTemporaryFile_args.py

temp: <open file '<fdopen>', mode 'w+b' at 0x1004481e0>

temp.name: /tmp/prefix_UyCzjc_suffix

tempfile.mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])

mkstemp方法用于创建一个临时文件。该方法仅仅用于创建临时文件,调用tempfile.mkstemp函数后,返回包含两个元素的元组,第一个元素指示操作该临时文件的安全级别,第二个元素指示该临时文件的路径。参数suffix和prefix分别表示临时文件名称的后缀和前缀;dir指定了临时文件所在的目录,如果没有指定目录,将根据系统环境变量TMPDIRTEMP或者TMP的设置来保存临时文件;参数text指定了是否以文本的形式来操作文件,默认为False,表示以二进制的形式来操作文件。

tempfile.mktemp([suffix=''[, prefix='tmp'[, dir=None]]])

mktemp用于返回一个临时文件的路径,但并不创建该临时文件。

tempfile.tempdir

该属性用于指定创建的临时文件(夹)所在的默认文件夹。如果没有设置该属性或者将其设为None,Python将返回以下环境变量TMPDIR, TEMP, TEMP指定的目录,如果没有定义这些环境变量,临时文件将被创建在当前工作目录。

tempfile.gettempdir()

gettempdir()则用于返回保存临时文件的文件夹路径。

转:https://www.cnblogs.com/captain_jack/archive/2011/01/19/1939555.html

Python模块学习——tempfile的更多相关文章

  1. 【转】Python模块学习 - fnmatch & glob

    [转]Python模块学习 - fnmatch & glob 介绍 fnmatch 和 glob 模块都是用来做字符串匹配文件名的标准库. fnmatch模块 大部分情况下使用字符串匹配查找特 ...

  2. 【目录】Python模块学习系列

    目录:Python模块学习笔记 1.Python模块学习 - Paramiko  - 主机管理 2.Python模块学习 - Fileinput - 读取文件 3.Python模块学习 - Confi ...

  3. Python模块学习filecmp文件比较

    Python模块学习filecmp文件比较 filecmp模块用于比较文件及文件夹的内容,它是一个轻量级的工具,使用非常简单.python标准库还提供了difflib模块用于比较文件的内容.关于dif ...

  4. python模块学习第 0000 题

    将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果. 类似于图中效果: 好可爱>%<! 题目来源:https://github.com/Yixiao ...

  5. Python模块学习:logging 日志记录

    原文出处: DarkBull    许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net ...

  6. 解惑Python模块学习,该如何着手操作...

    Python模块 晚上和朋友聊天,说到公司要求精兵计划,全员都要有编程能力.然后C.Java.Python-对于零基础入门的,当然是选择Python的人较多了.可朋友说他只是看了简单的语法,可pyth ...

  7. Python模块学习

    6. Modules If you quit from the Python interpreter and enter it again, the definitions you have made ...

  8. Python模块学习系列

    python模块-time python模块-datetime python模块-OS模块详解

  9. Python模块学习遇到的问题

    Python使用import导入模块时报ValueError: source code string cannot contain null bytes的解决方案 Python使用import导入模块 ...

随机推荐

  1. [转载]在VirtualBox中收缩虚拟磁盘映像文件

    原文地址:在VirtualBox中收缩虚拟磁盘映像文件作者:bobby 由于经常要测试一些软件,我在VirtualBox虚拟机中安装了一套Windows.使用过虚拟机的朋友都知道,为了节省硬盘空间,一 ...

  2. <转>lua解释执行脚本流程

    本文转自:http://www.cnblogs.com/zxh1210603696/p/4458473.html #include "lua.hpp" #include <i ...

  3. socket 995 错误 boost

    这个错误的中文解释是:由于线程退出或应用程序请求,已中止 I/O 操作. 最近几天学习boost asio 在抄官方的一个实例代码时遇到 了,这个错误搞了我三天才解决,就是在一行代码中少了一个 s 所 ...

  4. 【虚拟化系列】VMware vSphere 5.1 网络管理

       网络是VMware vSphere 5.1的基础,所有虚拟机都需要网络来进行通信.如果将所有的虚拟机都看成是物理机,则在网络拓扑上,需要网卡和交换机等不同的网络连接设备和方式.而在虚拟化中,这些 ...

  5. 【基础】centos 6.X 下修改图形界面为命令行界面(单用户救援模式)

    1. Linux开机引导的时候,按键盘上的e 就可以进入进入GRUB菜单界面. 2.在出现GRUB引导画面时(CentOS(2.6.18-274**)),按字母e键,进入GRUB编辑状态: 3.把光标 ...

  6. mac 终端添加颜色

    1.打开终端,然后找到终端偏好设置,选择自己喜欢的颜色 2.然后切换到当前用户的家目录: cd ~ 3.打开文件,开始编辑".bash_profile", 添加下面两句 expor ...

  7. Linux下出现command not found的解决办法

    不管是普通用户还是ROOT用户,修改~/.bash_profile文件,在文件最后加上:export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/u ...

  8. 手动修改magento域名

    So it turns out the problem was that Apache didn't have write permissions to the WEBROOT/var directo ...

  9. TensorFlow 基本概念

    一.概述 使用图(graph)来表示计算任务 在会话(Session)的上下文(context)中执行图(graph) 使用tensor表示数据 通过 变量(Variable)维护状态 使用 feed ...

  10. win7 32位 安装opencv-python后,运行时提示 "from .cv2 import *: DLL load failed: 找不到指定的模块" 的解决办法

    安装opencv后,运行一个测试程序提示"from .cv2 import *: DLL load failed: 找不到指定的模块".于是百度一下解决办法,结果试了N多方法后也没 ...