Python tempfile模块学习笔记(临时文件)


Posted in Python onMay 25, 2014

tempfile.TemporaryFile

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

实例一:

import os
import tempfileprint '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权限创建文件,在任何平台中都是如此,并且程序可以对它进行读写。这个例子说明了普通创建文件的方法与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权限创建文件,在任何平台中都是如此,并且程序可以对它进行读写。

实例二:

import os
import tempfiletemp = 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'。

实例三:

import tempfilef = 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属性访问它的名字

import os
import tempfiletemp = 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

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

import os
import tempfiledirectory_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

实例:

import tempfiletemp = 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指定了临时文件所在的目录,如果没有指定目录,将根据系统环境变量TMPDIR, TEMP或者TMP的设置来保存临时文件;参数text指定了是否以文本的形式来操作文件,默认为False,表示以二进制的形式来操作文件。

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

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

tempfile.tempdir

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

tempfile.gettempdir()

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

 

Python 相关文章推荐
python操作摄像头截图实现远程监控的例子
Mar 25 Python
Python中使用logging模块打印log日志详解
Apr 05 Python
Python中的localtime()方法使用详解
May 22 Python
浅谈Python爬取网页的编码处理
Nov 04 Python
利用python将json数据转换为csv格式的方法
Mar 22 Python
Appium Python自动化测试之环境搭建的步骤
Jan 23 Python
python基于pdfminer库提取pdf文字代码实例
Aug 15 Python
Python 函数用法简单示例【定义、参数、返回值、函数嵌套】
Sep 20 Python
python字符串判断密码强弱
Mar 18 Python
Python函数必须先定义,后调用说明(函数调用函数例外)
Jun 02 Python
解决导入django_filters不成功问题No module named 'django_filter'
Jul 15 Python
Python Tricks 使用 pywinrm 远程控制 Windows 主机的方法
Jul 21 Python
Python logging模块学习笔记
May 24 #Python
Python学习笔记之常用函数及说明
May 23 #Python
从零学python系列之教你如何根据图片生成字符画
May 23 #Python
从零学python系列之从文件读取和保存数据
May 23 #Python
从零学python系列之浅谈pickle模块封装和拆封数据对象的方法
May 23 #Python
从零学python系列之新版本导入httplib模块报ImportError解决方案
May 23 #Python
从零学python系列之数据处理编程实例(二)
May 22 #Python
You might like
php adodb连接不同数据库
2009/03/19 PHP
DEDE采集大师官方留后门的删除办法
2011/01/08 PHP
php中判断文件空目录是否有读写权限的函数代码
2012/08/07 PHP
php把数据表导出为Excel表的最简单、最快的方法(不用插件)
2014/05/10 PHP
php 升级到 5.3+ 后出现的一些错误,如 ereg(); ereg_replace(); 函数报错
2015/12/07 PHP
PHP页面跳转实现延时跳转的方法
2016/12/10 PHP
PHP使用第三方即时获取物流动态实例详解
2017/04/27 PHP
thinkPHP+LayUI 流加载实现功能
2019/09/27 PHP
jQuery之过滤元素操作小结
2013/11/30 Javascript
angularJS 中input示例分享
2015/02/09 Javascript
jQuery插件实现静态HTML验证码校验
2015/11/06 Javascript
深入学习JavaScript的AngularJS框架中指令的使用方法
2016/03/05 Javascript
EasyUi combotree 实现动态加载树节点
2016/04/01 Javascript
javascript insertAfter()定义与用法示例
2016/07/25 Javascript
基于jQuery实现歌词滚动版音乐播放器的代码
2016/09/17 Javascript
JavaScript制作颜色反转小游戏
2016/09/25 Javascript
dul无法加载bootstrap实现unload table/user恢复
2016/09/29 Javascript
详解JavaScript中js对象与JSON格式字符串的相互转换
2017/02/14 Javascript
nodejs后台集成ueditor富文本编辑器的实例
2017/07/11 NodeJs
Vue中插入HTML代码的方法
2018/09/21 Javascript
使用Python实现下载网易云音乐的高清MV
2015/03/16 Python
Python中的浮点数原理与运算分析
2017/10/12 Python
python 自动去除空行的实例
2018/07/24 Python
详解Python中的测试工具
2019/06/09 Python
使用pandas的box_plot去除异常值
2019/12/10 Python
如何通过python实现人脸识别验证
2020/01/17 Python
Python tkinter界面实现历史天气查询的示例代码
2020/08/23 Python
美国著名的家居用品购物网站:Bed Bath & Beyond
2018/01/05 全球购物
Desigual德国官网:在线购买原创服装
2018/03/27 全球购物
拓展培训心得体会
2014/01/04 职场文书
新法人代表任命书
2014/06/06 职场文书
优秀班主任材料
2014/12/16 职场文书
2015年大学生村官工作总结
2015/04/21 职场文书
百万英镑观后感
2015/06/09 职场文书
golang 实现对Map进行键值自定义排序
2021/04/28 Golang
jackson json序列化实现首字母大写,第二个字母需小写
2021/06/29 Java/Android