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

(0)

相关推荐

  • python创建临时文件夹的方法

    本文实例讲述了python创建临时文件夹的方法.分享给大家供大家参考.具体实现方法如下: import tempfile, os tempfd, tempname = tempfile.mkstemp('.suffix') os.write(tempfd, "aString") # or, if you want a file-object: os.fdopen(tempfd, 'w+') os.close(tempfd) os.unlink(tempname) 希望本文所述对大家的P

  • Python写的创建文件夹自定义函数mkdir()

    Python对文件的操作还算是方便的,只需要包含os模块进来,使用相关函数即可实现目录的创建. 主要涉及到三个函数: 1.os.path.exists(path) 判断一个目录是否存在 2.os.makedirs(path) 多层创建目录 3.os.mkdir(path) 创建目录 直接上代码: 复制代码 代码如下: def mkdir(path):     # 引入模块     import os       # 去除首位空格     path=path.strip()     # 去除尾部

  • Python简单删除目录下文件以及文件夹的方法

    本文实例讲述了Python简单删除目录下文件以及文件夹的方法.分享给大家供大家参考.具体如下: #!/usr/bin/env python import os import shutil filelist=[] rootdir="/home/zoer/aaa" filelist=os.listdir(rootdir) for f in filelist: filepath = os.path.join( rootdir, f ) if os.path.isfile(filepath):

  • python使用cStringIO实现临时内存文件访问的方法

    本文实例讲述了python使用cStringIO实现临时内存文件访问的方法.分享给大家供大家参考.具体分析如下: 如果希望从网络读取文件进行处理,但是又不希望保存文件到硬盘,可以使用cStringIO模块进行处理 res = urllib2.urlopen(pic,timeout=10) f = cStringIO.StringIO(res.read()) f 是一个文件对象, 它和:f = open('c:/1.jpg','rw')  打开的文件一样 可以向操作本地文件一样对内存文件进行读写

  • Python引用(import)文件夹下的py文件的方法

    Python的import包含文件功能就跟PHP的include类似,但更确切的说应该更像是PHP中的require,因为Python里的import只要目标不存在就报错程序无法往下执行.要包含目录里的文件,PHP中只需要给对路径就OK.Python中则不同,下面来看看这个例子. 目录结构: a.py 要 import dir目录下的 b.py 文件.a.py代码如下: 复制代码 代码如下: # coding=utf-8 "import dir 目录下的 b.py 文件"   impo

  • Python遍历指定文件及文件夹的方法

    本文实例讲述了Python遍历指定文件及文件夹的方法.分享给大家供大家参考.具体如下: 初次编写: import os def searchdir(arg,dirname,names): for filespath in names: open ('c:\\test.txt','a').write('%s\r\n'%(os.path.join(dirname,filespath))) if __name__=="__main__": paths="g:\\" os.

  • python使用循环实现批量创建文件夹示例

    代码很简单,其中用到了python的sys模块,大家参考使用吧 复制代码 代码如下: import os,sysbase = 'C:/'i = 1for j in range(100):    file_name = base+str(i)    os.mkdir(file_name)    i=i+1

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

    tempfile.TemporaryFile 如何你的应用程序需要一个临时文件来存储数据,但不需要同其他程序共享,那么用TemporaryFile函数创建临时文件是最好的选择.其他的应用程序是无法找到或打开这个文件的,因为它并没有引用文件系统表.用这个函数创建的临时文件,关闭后会自动删除. 实例一: 复制代码 代码如下: import osimport tempfile print 'Building a file name yourself:'filename = '/tmp/guess_my

  • Python os模块学习笔记

    一.os模块概述 Python os模块包含普遍的操作系统功能.例如文件的复制.创建.修改.删除文件及文件夹... 二.常用方法 1.os.listdir()   返回指定目录下的所有文件和目录名. 2.os.remove()  删除一个文件. 3.os.system()  运行shell命令. 4.os.path.split()   函数返回一个路径的目录名和文件名 5.os.path.isfile()和os.path.isdir()   函数分别检验给出的路径是一个文件还是目录,返回值分别为

  • Python logging模块学习笔记

    模块级函数 logging.getLogger([name]):返回一个logger对象,如果没有指定名字将返回root loggerlogging.debug().logging.info().logging.warning().logging.error().logging.critical():设定root logger的日志级别logging.basicConfig():用默认Formatter为日志系统建立一个StreamHandler,设置基础配置并加到root logger中 示例

  • python网络编程学习笔记(二):socket建立网络客户端

    1.建立socket 建立socket对象需要搞清通信类型和协议家族.通信类型指明了用什么协议来传输数据.协议的例子包括IPv4.IPv6.IPX\SPX.AFP.对于internet通信,通信类型基本上都是AF_INET(和IPv4对应).协议家族一般表示TCP通信的SOCK_STREAM或者表示UDP通信的SOCK_DGRAM.因此对于TCP通信,建立一个socket连接的语句为:s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)对于UDP通

  • Python GUI编程学习笔记之tkinter中messagebox、filedialog控件用法详解

    本文实例讲述了Python GUI编程学习笔记之tkinter中messagebox.filedialog控件用法.分享给大家供大家参考,具体如下: 相关内容: messagebox 介绍 使用 filedialog 介绍 使用 首发时间:2018-03-04 22:18 messagebox: 介绍:messagebox是tkinter中的消息框.对话框 使用: 导入模块:import tkinter.messagebox 选择消息框的模式: 提示消息框:[返回"ok"] tkint

  • Python GUI编程学习笔记之tkinter控件的介绍及基本使用方法详解

    本文实例讲述了Python GUI编程学习笔记之tkinter控件的介绍及基本使用方法.分享给大家供大家参考,具体如下: 相关内容: tkinter的使用 1.模块的导入 2.使用 3.控件介绍 Tk Button Label Frame Toplevel Menu Menubutton Canvas Entry Message Text Listbox Checkbutton Radiobutton Scale Scrollbar 首发时间:2018-03-04 16:39 Python的GU

  • node的process以及child_process模块学习笔记

    在死磕进程一个礼拜后,终于把晦涩难懂文档看明白了,准备把自己的理解分享给大家,也希望大家能指出一些意见 进程的概念 在Node.js中每个应用程序都是一个进程类的实例对象. 使用process对象代表应用程序,这是一个全局对象,可以通过它来获取Node.jsy应用程序以及运行该程序的用户.环境等各种信息的属性.方法和事件. 进程中几个重要的属性 stdin 标准输入可读流 stdout 标准输入可写流 stderr 标准错误输出流 argv 终端输入参数数组 env 操作系统环境信息 pid 应

  • 详解node child_process模块学习笔记

    NodeJs是一个单进程的语言,不能像Java那样可以创建多线程来并发执行.当然在大部分情况下,NodeJs是不需要并发执行的,因为它是事件驱动性永不阻塞.但单进程也有个问题就是不能充分利用CPU的多核机制,根据前人的经验,可以通过创建多个进程来充分利用CPU多核,并且Node通过了child_process模块来创建完成多进程的操作. child_process模块给予node任意创建子进程的能力,node官方文档对于child_proces模块给出了四种方法,映射到操作系统其实都是创建子进程

  • Python GUI编程学习笔记之tkinter事件绑定操作详解

    本文实例讲述了Python GUI编程学习笔记之tkinter事件绑定操作.分享给大家供大家参考,具体如下: 相关内容: command bind protocol 首发时间:2018-03-04 19:26 command: command是控件中的一个参数,如果使得command=函数,那么点击控件的时候将会触发函数 能够定义command的常见控件有: Button.Menu- 调用函数时,默认是没有参数传入的,如果要强制传入参数,可以考虑使用lambda from tkinter imp

  • Python GUI编程学习笔记之tkinter界面布局显示详解

    本文实例讲述了Python GUI编程学习笔记之tkinter界面布局显示.分享给大家供大家参考,具体如下: 相关内容: pack 介绍 常用参数 使用情况 常用函数 grid 介绍 常用参数 使用情况 常用函数 place 介绍 常用参数 使用情况 常用函数 首发时间:2018-03-04 14:20 pack: 介绍: pack几何管理器按行或列打包小部件. 可以使用填充fill,展开expand和靠边side等选项来控制此几何体管理器. pack的排放控件的形式就像将一个个控件按大小从上到

随机推荐