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

 更新时间:2014年05月25日 10:41:03   作者:  
这篇文章主要介绍了Python tempfile模块学习笔记,着重讲解了模块下的几个函数,需要的朋友可以参考下

tempfile.TemporaryFile

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

实例一:

复制代码 代码如下:

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

实例三:

复制代码 代码如下:

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

复制代码 代码如下:

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

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

复制代码 代码如下:

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

实例:

复制代码 代码如下:

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

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

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

tempfile.tempdir

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

tempfile.gettempdir()

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

 

相关文章

  • 浅谈matplotlib 绘制梯度下降求解过程

    浅谈matplotlib 绘制梯度下降求解过程

    这篇文章主要介绍了浅谈matplotlib 绘制梯度下降求解过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • Python强制重新安装Python包之pip的高级使用技巧

    Python强制重新安装Python包之pip的高级使用技巧

    这篇文章主要介绍了如何使用pip强制重新安装Python包的几种方法,包括使用--upgrade、--force-reinstall和--no-deps选项,这些方法可以帮助解决包损坏、依赖问题或其他需要重新安装包的情况,需要的朋友可以参考下
    2025-03-03
  • 基于Python OpenCV实现图像的覆盖

    基于Python OpenCV实现图像的覆盖

    本文将基于Python、OpenCV和Numpy实现图像的覆盖,即小图像覆盖在大图像上。文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2022-02-02
  • python打印n位数“水仙花数”(实例代码)

    python打印n位数“水仙花数”(实例代码)

    这篇文章主要介绍了python打印n位数“水仙花数”,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-12-12
  • python中re.findall() 的使用案例

    python中re.findall() 的使用案例

    re.findall() 函数是 python 中正则表达式模块(re)的一个重要函数,它可以根据正则表达式搜索字符串,并返回匹配的字符串列表,这篇文章给大家介绍了python中re.findall() 的使用案例,感兴趣的朋友跟随小编一起看看吧
    2023-09-09
  • Python 查看数据类型与格式

    Python 查看数据类型与格式

    这篇文章主要介绍了Python 查看数据类型与格式方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • python服务器与android客户端socket通信实例

    python服务器与android客户端socket通信实例

    这篇文章主要介绍了python服务器与android客户端socket通信的实现方法,实例形式详细讲述了Python的服务器端实现原理与方法,以及对应的Android客户端实现方法,需要的朋友可以参考下
    2014-11-11
  • 如何使用python生成大量数据写入es数据库并查询操作

    如何使用python生成大量数据写入es数据库并查询操作

    这篇文章主要介绍了如何使用python生成大量数据写入es数据库并查询操作,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • Python数据清洗之利用pandas筛选数据详解

    Python数据清洗之利用pandas筛选数据详解

    这篇文章主要介绍了Python数据清洗之利用pandas筛选数据详解,Pandas是一个用于数据分析和处理的Python库,它提供了高效的数据结构和数据分析工具,使得数据的清洗、转换、分析和可视化变得更加容易和灵活,需要的朋友可以参考下
    2023-08-08
  • 基于python的selenium两种文件上传操作实现详解

    基于python的selenium两种文件上传操作实现详解

    这篇文章主要介绍了基于python的selenium两种文件上传操作实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09

最新评论