【问题标题】:Find file based on portions of the name: Python根据名称的部分查找文件:Python
【发布时间】:2021-06-04 15:05:59
【问题描述】:

如何根据部分名称查找文件或文件夹?例如:

我有两个产品 A 和 B,它们的序列号分别为 SN1 和 SN2。我也知道 X 的值,但我不知道日期和时间的值。 我想找到名为 A_SN1_B_SN2_date_time_stationX 的文件夹中的文件名 文件名类似于 A_SN1_B_SN2_date_time_stationX_log.rtf

我如何在不知道日期或时间的情况下找到这些???

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    Python 可以使用 OS 包轻松搜索文件名

        import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    

    【讨论】:

    • 问题是我不知道文件名!!!文件名包含一些更改的字符,例如时间和日期。如何提取选定目录中的文件/文件夹的名称?