【问题标题】:Deleting all files in a folder in Python在Python中删除文件夹中的所有文件
【发布时间】:2015-07-02 08:15:22
【问题描述】:

我正在尝试用 Python 编写一个程序,该程序将删除 %temp% 路径中的所有文件,也称为 C:\Users\User\AppData\Local\Temp

我该怎么做?我正在使用 Python 3.4。

【问题讨论】:

标签: python python-3.x temporary-files temp


【解决方案1】:

一般情况下,您可以使用shutil.rmtree() 删除文件夹中的所有文件/目录:

#!/usr/bin/env python
import shutil
import tempfile

dirpath = tempfile.mkdtemp()
try:
    # use the temporary directory here
    ...
finally:
    shutil.rmtree(dirpath) # clean up

如果你需要的话,上面可以写得更简单(从头开始创建一个临时目录):

#!/usr/bin/env python3
import tempfile

with tempfile.TemporaryDirectory() as dir:
    print(dir.name) # use the temporary directory here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多