python 临时文件

2019-10-21 15:28:50 浏览数 (1)

tempfile.TemporaryFile

from tempfile import TemporaryFile

with TemporaryFile('w t') as f: # Read/write to the file f.write('Hello Worldn') f.write('Testingn')

代码语言:javascript复制
# Seek back to beginning and read the data
f.seek(0)
data = f.read()

Temporary file is destroyed

带名字临时文件NamedTemporaryFile

from tempfile import NamedTemporaryFile

with NamedTemporaryFile('w t') as f: print('filename is:', f.name) ...

File automatically destroyed

delete=false

with NamedTemporaryFile('w t', delete=False) as f: print('filename is:', f.name) ...

prefix

f = NamedTemporaryFile(prefix='mytemp', suffix='.txt', dir='/tmp') f.name '/tmp/mytemp8ee899.txt'

TemporaryDirectory

from tempfile import TemporaryDirectory

with TemporaryDirectory() as dirname: print('dirname is:', dirname) # Use the directory ...

Directory and all contents destroyed

import tempfile tempfile.mkstemp() (3, '/var/folders/7W/7WZl5sfZEF0pljrEB1UMWE TI/-Tmp-/tmp7fefhv') tempfile.mkdtemp() '/var/folders/7W/7WZl5sfZEF0pljrEB1UMWE TI/-Tmp-/tmp5wvcv6' tempfile.gettempdir() '/var/folders/7W/7WZl5sfZEF0pljrEB1UMWE TI/-Tmp-'

0 人点赞