温馨提示×

python怎么删除文件夹下的所有文件

小亿
91
2024-01-11 10:12:35
栏目: 编程语言

你可以使用 os 模块中的 listdir 函数来获取文件夹下的所有文件名,并使用 os.remove 函数来删除每个文件。以下是一个示例代码:

import os

def delete_files_in_folder(folder):
    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                delete_files_in_folder(file_path)
                os.rmdir(file_path)
        except Exception as e:
            print('Failed to delete %s. Reason: %s' % (file_path, e))

folder_path = '/path/to/folder'
delete_files_in_folder(folder_path)

在这个示例中,delete_files_in_folder 函数接受一个文件夹路径作为参数,并遍历文件夹中的每个文件和子文件夹。如果是文件或符号链接,则使用 os.unlink 函数删除文件。如果是文件夹,则递归调用 delete_files_in_folder 函数删除子文件夹中的所有文件,并使用 os.rmdir 函数删除文件夹本身。

0