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

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

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

我的问题如下:

我正在比较来自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,我还将考虑您的代码,再次感谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-