文章内容

2023/2/7 16:20:47,作 者: 黄兵

Python 如何删除指定目录下所有文件

如果我们使用 Python 删除指定目录下面的所有文件,下面是示例代码:

import os

def delete_files_in_dir(dir_path):
    for filename in os.listdir(dir_path):
        file_path = os.path.join(dir_path, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                os.rmdir(file_path)
        except Exception as e:
            print(f"Failed to delete {file_path}: {e}")

# 调用函数删除指定目录下的所有文件
delete_files_in_dir("/path/to/dir")

该代码使用 os.listdir 函数获取指定目录下的所有文件名,然后使用 os.unlink 函数删除文件,使用 os.rmdir 函数删除目录。

分享到:

发表评论

评论列表