应用程序经常要保存一些临时的信息,这些信息不是特别重要,
没有必要写在配置文件里,但又不能没有,这时候就可以把这些信息写到临时文件里。
其实很多程序在运行的时候,都会产生一大堆临时文件,有些用于保存日志,
有些用于保存一些临时数据,还有一些保存一些无关紧要的设置。
在windows操作系统中,临时文件一般被保存在这个文件夹下:
C:/Documents and Settings/User/Local Settings/Temp
。
其实最常用的IE浏览器在浏览网页的时候,会产生大量的临时文件,
这些临时文件一般是浏览过的网页的本地副本。
Python提供了一个 tempfile
模块,用来对临时数据进行操作。
mkstemp()
方法用于创建一个临时文件。该方法仅仅用于创建临时文件,
调用 tempfile.mkstemp()
函数后,
返回包含两个元素的元组,第一个元素指示操作该临时文件的安全级别,
第二个元素指示该临时文件的路径。
参数 suffix
和 prefix
分别表示临时文件名称的后缀和前缀;
dir
指定了临时文件所在的目录,如果没有指定目录,
将根据系统环境变量 TMPDIR
, TEMP
或者 TMP
的设置来保存临时文件;
参数 text
指定了是否以文本的形式来操作文件,
默认为 False
,表示以二进制的形式来操作文件。
tempfile.mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])
: 该函数用于创建一个临时文件夹。参数的意思与tempfile.mkdtemp
一样。 它返回临时文件夹的绝对路径。tempfile.mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]])
:mktemp()
用于返回一个临时文件的路径,但并不创建该临时文件。tempfile.mktemp([suffix=''[, prefix='tmp'[, dir=None]]])
: 该属性用于指定创建的临时文件(夹)所在的默认文件夹。 如果没有设置该属性或者将其设为None
, Python将返回以下环境变量TMPDIR
,TEMP
,TEMP
指定的目录, 如果没有定义这些环境变量,临时文件将被创建在当前工作目录。gettempdir()
则用于返回保存临时文件的文件夹路径:tempfile.gettempdir()
。TemporaryFile()
函数返回一个类文件 对象(file-like)用于临时数据保存(实际上对应磁盘上的一个临时文件)。 当文件对象被close
或者被del
的时候,临时文件将从磁盘上删除。mode
、bufsize
参数的单方与open()
函数一样;suffix
和prefix
指定了临时文件名的后缀和前缀;dir
用于设置临时文件默认的保存路径。 返回的类文件对象有一个file
属性,它指向真正操作的底层的file
对象。tempfile.TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])
tempfile.NamedTemporaryFile
函数的行为与tempfile.TemporaryFile
类似, 只不过它多了一个delete
参数,用于指定类文件对象close
或者被del
之后, 是否也一同删除磁盘上的临时文件(当delete = True
的时候,行为与TemporaryFile
一样)。tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
。tempfile.SpooledTemporaryFile
函数的行为与tempfile.TemporaryFile
类似。 不同的是向类文件对象写数据的时候,数据长度只有到达参数max_size
指定大小时, 或者调用类文件对象的fileno()
方法,数据才会真正写入到磁盘的临时文件中。tempfile.SpooledTemporaryFile([max_size=0[, mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]])
。
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)
Building a file name yourself: temp: <_io.BufferedRandom name='/tmp/guess_my_name.3287.txt'> temp.name: /tmp/guess_my_name.3287.txt
自动清理文件。
print ('TemporaryFile:')
temp = tempfile.TemporaryFile()
try:
print( 'temp:', temp)
print ('temp.name:', temp.name)
finally:
temp.close()
TemporaryFile: temp: <_io.BufferedRandom name=56> temp.name: 56
这个例子说明了普通创建文件的方法与 TemporaryFile()
的不同之处,
注意:用 TemporaryFile()
创建的文件没有文件名。
默认情况下使用 w+b
权限创建文件,在任何平台中都是如此,并且程序可以对它进行读写。
import os
import tempfile
temp = tempfile.TemporaryFile()
try:
temp.write('Some data'.encode())
temp.seek(0)
print (temp.read())
finally:
temp.close()
b'Some data'
写入后,需要使用 seek()
,为了以后读取数据。
如果想让文件以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()
first second
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))
temp: <tempfile._TemporaryFileWrapper object at 0x7f830ee27fe0> temp.name: /tmp/tmpa2wfeo95 Exists after close: False
尽管文件带有名字,但它仍然会在 close
后自动删除。
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()
temp: <tempfile._TemporaryFileWrapper object at 0x7f82fd616060> temp.name: /tmp/prefix_abm9cvn3_suffix
import os
import tempfile
directory_name = tempfile.mkdtemp()
print ( directory_name)
/tmp/tmpn_gr6_bc
自行清理目录。
os.removedirs(directory_name)
目录需要手动删除。