Skip to main content
 首页 » 编程设计

python之遍历目录并删除基于 Python 扩展名的文件

2025年05月04日15kenshinobiy

我有一个模拟以下内容的文件结构:

我一直有一个文件夹,那个文件夹里有一个EXCEL文件夹和一堆文本文件。每个 EXCEL 文件夹都有一堆 .xlsx 文件。

按照相同的结构,可以将相同的想法无限次地复制。我正在尝试进入每个目录的每个 EXCEL 文件夹,删除所有扩展名为 .xlsx 的文件并继续此过程,直到访问所有 EXCEL 文件夹。

这是我失败的一些代码:

def clean_out_excel_test_data(): 
    #For each folder in the test_log directory 
        #Open each folder 
            #for each_folder that contains the word EXCEL 
                #open each_folder 
                    #for each file in each_folder, remove it 
 
    log_directory = "test_log_data/" 
 
    for each_folder in sorted(os.listdir(log_directory)): 
        print each_folder + ' is in the root' 
        for each_folder2 in sorted(os.listdir('%s/%s'%(log_directory,each_folder))) if os.path.isdir(each_folder2): 
            print '\t-' + each_folder2 + ' is a sub-folder' 
            for each_excel_file in sorted(os.listdir('%s/%s/%s'%(log_directory,each_folder, each_folder2))): 
                print '\t\t-' + each_excel_file + ' is a sub excel file' 

我意识到我的代码很垃圾,但我想至少展示我的目标。

请您参考如下方法:

让os.walk为您处理目录遍历:

for root, dirs, files in os.walk('/path/to/test_log_data'): 
    if 'EXCEL' not in root: 
        continue 
    for fname in files: 
        if fname.endswith('.xlsx'): 
            os.remove(os.path.join(root, fname))