使用通配符在多个文件夹中搜索特定文件如果存在

问题描述

我已经在网上搜索过,并向人们询问了我的“简单”问题,但我没有令人满意的答案。

我的问题如下:

我正在比较来自Exhange的数据(以excel文件的形式保存在某些文件夹中)和系统中的数据(来自数据库SQL查询)。我正在设计一个工具,用于比较-到特定DATE的数据。我所有的交换数据文件名都基于特定的日期格式,某些字符串和excel文件格式也有所不同(有时是.xls,.xlsx,.xlsm)。

显然,我需要做的是编写一个循环来搜索从“ FROM”日期到“ TO”日期的所需文件。让我们花费从2020年7月7日到2020年7月13日的时间。也就是说,缺少2020年7月11日的文件。请记住,我的文件存储在某些位置,该位置使用MONTH等命名的多个子文件

示例:

C:\Users\VB\Desktop\VB\python\05
C:\Users\VB\Desktop\VB\python\06
C:\Users\VB\Desktop\VB\python\07

以下是我的文件名示例:

07.07.2020 - Bestscore.xls
07.07.2020 - Worstscore.xlsx
08.07.2020 - Bestscore.xls
08.07.2020 - Worstscore.xlsx
09.07.2020 - Bestscore.xls
09.07.2020 - Worstscore.xls
10.07.2020 - Bestscore.xls
10.07.2020 - Worstscore.xlsm
12.07.2020 - Bestscore.xls
12.07.2020 - Worstscore.xlsx

我的基本代码如下:

import os
from datetime import timedelta

startD = date(2020,7,10)
day= timedelta(days=1)
EndD = date(2020,13)

folder = 'C:\Users\VB\Desktop\VB\python'

while startD <= EndD:
    
    date=(startD.strftime("%d.%m.%Y"))
    file = date + '-Bestscore'
    file2 = date + '-Worstscore'

    **code IF file or file2 is found ---> do something **
    ** ELSE IF file or file2 is not found ---> print(file or file2 not found)

出现问题是因为我必须使用通配,并且需要搜索多个文件(有时我需要向后映射数据几个月,所以在不同的文件夹中搜索是一种必须)。

我尝试使用不同的功能来遍历多个文件夹:

  • os.walk()
  • glob.glob()
  • glob2.iglob()

但是它们都不符合我的要求。在循环时,这些函数会检查每个文件通配名称,并明显返回上面未正确命名的EACH文件名的“ else if”语句:

no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713

我不需要检查每个文件是否正确,我只想接收如下结果:

found 07.07.2020 - Bestscore.xls
found 07.07.2020 - Worstscore.xlsx
found 08.07.2020 - Bestscore.xls
found 08.07.2020 - Worstscore.xlsx
found 09.07.2020 - Bestscore.xls
found 09.07.2020 - Worstscore.xls
found 10.07.2020 - Bestscore.xls
found 10.07.2020 - Worstscore.xlsm
NOT found 11.07.2020 - Bestscore
NOT found 11.07.2020 - Worstscore
found 12.07.2020 - Bestscore.xls
found 12.07.2020 - Worstscore.xlsx

总而言之,我需要一个解决方案来使用通配符*搜索多个子文件夹,而不要使用IF语句检查每个文件

我正在学习python几个月,我认为这应该解决不了什么大问题,但对此我有些困惑。 解决此问题将使我的项目完成,因为其他所有工作都已开始:)

我将很高兴获得任何帮助。

谢谢。

解决方法

您的问题相当模糊:如果您可以提供有关文件系统结构的更多详细信息,那就太好了。

无论如何,我将您的问题解释如下:给一个要搜索的目录和两个日期(开始和结束),您想在这些日期内搜索两个不同的文件(BestScore和WorstScore)。如果存在,则执行某些操作,否则,打印警告。

示例:

  • 开始日期:2020年7月7日
  • 结束状态:2020年8月7日
  • 搜索目录:〜/ some / dir
  • 允许的文件扩展名:xls,xlsm,xlsx

这意味着我们正在寻找四个文件:

  • 〜/ some / dir / ..... / 07.07.2020-BestScore.xls
  • 〜/ some / dir / ..... / 07.07.2020-WorstScore.xlsx
  • 〜/ some / dir / ..... / 08.07.2020-BestScore.xlsm
  • 〜/ some / dir / ..... / 08.07.2020-WorstScore.xlsx

..,它们中的任何一个可能存在也可能不存在~/some/dir的某个子目录中。无论其他日期是否存在,我们对其他日期的其他文件都不感兴趣。

首先,我们需要一些辅助功能。我们从您想对现有文件做任何事情开始,这里以print表示,

def do_something_with(file_path):
  # do something with file ..
  print("doing something with '%s' .." % file_path)

确定目录条目是否是文件以及文件类型正确的功能

import os
def is_xls_file(file_path):
  return (os.path.isfile(file_path) and (
    file_path.endswith(".xls") or
    file_path.endswith(".xlsm") or
    file_path.endswith(".xlsx")))

用于创建我们要搜索的文件的字典的功能

from datetime import date,timedelta
def files_to_find(start_date,end_date,filenames):
  files = {}
  d = start_date
  while d != end_date:
    for fn in filenames:
      files["%s - %s" % (d.strftime("%d.%m.%Y"),fn)] = None
    d += timedelta(days=1)
  return files

然后是实际的搜索功能:我们执行os.walk(),遍历所有文件和子目录。如果找到所需文件,我们会将其路径存储在files_to_find词典中。

def find_files(files_to_find,search_dir):
  for dirpath,subdirs,files in os.walk(search_dir):
    for f in files:
      for ftf in files_to_find:
        # add .lower() for case-insensitivity
        if ftf.lower() in f.lower() and is_xls_file(os.path.join(dirpath,f)):
          files_to_find[ftf] = os.path.join(dirpath,f)
  return files_to_find

我们可以遍历file_to_find字典并对存在的文件执行所需的任何操作,并为不存在的文件打印警告,

startD = date(2020,7,10)
EndD = date(2020,13)
filenames = ["bestscore","worstscore"] # the search is case-insensitve
search_dir = "./fold1/fold2"

to_find = files_to_find(startD,EndD,filenames)
found = find_files(to_find,search_dir)

for f,abs_path in found.items():
  if abs_path is None:
    print("Was unable to find '%s'" % f)
  else:
    do_something_with(abs_path)

下面是运行示例的屏幕快照,其中使用了来自上方的输入,显示了文件系统的结果。如前所述,该脚本将在此示例中搜索每个日期的六个文件(即Best-和WorstScore)。因此,它会精确地打印 六个事件,每个文件一个:是否找到它。

example run

,

非常感谢您的详细解释,谢谢。我承认我的问题描述比较模糊而不是清楚。 同时,我已经弄清楚如何处理我的问题,请参见下文: 在我的IT同事的帮助下,我们找到了使用 glob.glob函数的解决方案。

import glob
from datetime import timedelta,date

startD = date(2020,10)
day= timedelta(days=1)
EndD = date(2020,15)

path = '//some folder'
#print(path)

while startD <= EndD:
    
    date=(startD.strftime("%Y%m%d"))
    file = date + '_best_score*'  # wildcard because of various extension
    file2 = date + '_worst_score*' ## wildcard because of various extension
    result = glob.glob(f'{path}/**/{file}',recursive=True) # search through all subfolders of "path"
    result2 = glob.glob(f'{path}/**/{file2}',recursive=True) # search through all subfolders of "path"
  
    if result or result2:
        print("found file",file)
        print("found file",file2)

    else:
        print("missing",file)
        print("missing",file2)

    startD += day

在我看来,使用/ ** /可以解决问题,因为我有许多子文件夹,它们的名称不同。 此代码仅在找到两个文件时才起作用,因此我们修改了if语句。由于glob.glob函数返回两个可能的列表,我们将result和result2合并到结果列表中。

results = result + result2
if len(results) == 2:
        print(results[0]))
        print(results[1]))
elif 1 > len(results) < 2:
    if "best_score" in str(results):
        print("missing",file2)
    else:
        print("missing",file)
else:
    print("missing",file)
    print("missing",file2)

startD += day

您怎么看?

为了进一步学习python,我还将考虑您的代码,再次感谢!