6.6.4 临时目录
需要多个临时文件时,可能更方便的做法是用TemporaryDirectory创建一个临时目录,并打开该目录中的所有文件。
import pathlib
import tempfile
with tempfile.TemporaryDirectory() as directory_name:
the_dir = pathlib.Path(directory_name)
print(the_dir)
a_file = the_dir / 'a_file.txt'
a_file.write_text('This file is deleted.')
print('Directory exists after?',the_dir.exists())
print('Contents after:',list(the_dir.glob('*')))
上下文管理器会生成目录名,可以在上下文块中用来建立其他文件名。
运行结果: