首页
学习
活动
专区
圈层
工具
发布

python 临时文件

tempfile.TemporaryFile

from tempfile import TemporaryFile

with TemporaryFile('w+t') as f: # Read/write to the file f.write('Hello World\n') f.write('Testing\n')

代码语言:javascript
代码运行次数:0
复制
# 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-'

下一篇
举报
领券