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

38次阅读
没有评论

共计 671 个字符,预计需要花费 2 分钟才能阅读完成。

你可以使用 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 函数删除文件夹本身。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-02-05发表,共计671字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)