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

时间:2022-05-27 02:32:08 

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()则用于返回保存临时文件的文件夹路径。

 

标签:Python,tempfile
0
投稿

猜你喜欢

  • 简单谈谈Python中的几种常见的数据类型

    2021-05-24 06:20:48
  • Python基础入门之seed()方法的使用

    2021-11-17 04:10:19
  • JS实现json数组排序操作实例分析

    2024-04-18 09:44:25
  • access改mdb为asp所带来的灾难 附mdb防下载方法

    2011-03-03 11:07:00
  • SQL Server简单查询示例汇总

    2024-01-27 12:19:41
  • Go 实战单队列到优先级队列实现图文示例

    2024-05-22 10:19:03
  • 实例讲解使用原生JavaScript处理AJAX请求的方法

    2024-04-16 08:47:16
  • 详解appium+python 启动一个app步骤

    2021-12-19 02:44:55
  • windows下python安装小白入门教程

    2022-01-05 08:45:44
  • 自动更新程序的设计框架

    2009-08-12 13:00:00
  • javascript使用正则表达式检测IP地址

    2024-03-15 11:06:52
  • Swin Transformer图像处理深度学习模型

    2022-01-16 22:32:08
  • Python下的常用下载安装工具pip的安装方法

    2021-08-31 05:05:35
  • jquery $(document).ready() 与window.onload的区别

    2024-04-19 10:23:59
  • JS实现点击li标签弹出对应的索引功能【案例】

    2024-04-17 10:24:23
  • Python及PyCharm下载与安装教程

    2022-10-04 08:19:54
  • MySQL高级特性——数据表分区的概念及机制详解

    2024-01-28 12:30:28
  • 使用Title提升可访问性

    2009-04-04 17:06:00
  • Python使用matplotlib绘制三维参数曲线操作示例

    2021-03-30 05:55:31
  • php中Ctype函数用法详解

    2023-06-19 01:43:13
  • asp之家 网络编程 m.aspxhome.com