duh*_*onn 125 python temporary-files temporary-directory
如何在python中创建临时目录并获取路径/文件名
Phi*_*ipp 186
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
Run Code Online (Sandbox Code Playgroud)
cdu*_*001 36
为了扩展另一个答案,这里是一个相当完整的例子,即使在例外情况下也可以清理tmpdir:
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
cleanup()
@contextlib.contextmanager
def tempdir():
dirpath = tempfile.mkdtemp()
def cleanup():
shutil.rmtree(dirpath)
with cd(dirpath, cleanup):
yield dirpath
def main():
with tempdir() as dirpath:
pass # do something here
Run Code Online (Sandbox Code Playgroud)
Pau*_*eux 19
文档建议使用TemporaryDirectory上下文管理器,它会创建一个临时目录,并在退出上下文管理器时自动删除它。使用pathlib的斜杠运算符/ 来操作路径,我们可以在临时目录中创建一个临时文件,然后从临时文件中写入和读取数据,如下所示:
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmpdirname:
temp_dir = Path(tmpdirname)
file_name = temp_dir / "test.txt"
file_name.write_text("bla bla bla")
print(temp_dir, temp_dir.exists())
# /tmp/tmp81iox6s2 True
print(file_name, "contains", file_name.open().read())
# /tmp/tmp81iox6s2/test.txt contains bla bla bla
Run Code Online (Sandbox Code Playgroud)
在上下文管理器之外,临时文件和临时目录已被破坏
print(file_name, file_name.exists())
# /tmp/tmp81iox6s2/test.txt False
print(temp_dir, temp_dir.exists())
# /tmp/tmp81iox6s2 False
Run Code Online (Sandbox Code Playgroud)
Nag*_*gev 15
在Python 3,TemporaryDirectory中临时文件可以使用的模块。
这直接来自示例:
import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
print('created temporary directory', tmpdirname)
# directory and contents have been removed
Run Code Online (Sandbox Code Playgroud)
如果您想将目录保留更长的时间,则可以执行类似的操作(不是来自示例):
import tempfile
import shutil
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
shutil.rmtree(temp_dir.name)
Run Code Online (Sandbox Code Playgroud)
正如@MatthiasRoelandts指出的那样,文档还指出“可以通过调用该cleanup()方法来显式清理目录”。
And*_*ler 12
在python 3.2及更高版本中,stdlib中有一个有用的上下文管理器https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory
如果我正确理解你的问题,你还想知道临时目录中生成的文件的名称吗?如果是这样,请尝试以下操作:
import os
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
# generate some random files in it
files_in_dir = os.listdir(tmp_dir)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73676 次 |
| 最近记录: |