【问题标题】:Filtering only files in a particular extension - Python仅过滤特定扩展名中的文件 - Python
【发布时间】:2015-07-23 19:48:45
【问题描述】:

我有以下脚本在Python 中搜索具有特定扩展名的文件

  13 def list_xml_reports(d, extensions):
  14     matches = []
  15     print extensions
  16     for root, dirname, filenames in os.walk(d):
  17         for extension in extensions:
  18             for filename in fnmatch.filter(filenames, extension):
  19                 matches.append(os.path.join(root, filename))
  20     return set(matches)
  21 
  22 print list_xml_reports("/root/my_dir", ("*junitReport.xml"))

但是,不是只返回以 *junitReport.xml 结尾的文件,而是返回所有内容(*.log*build.xml*.txt*changelog.xml)......为什么会这样?

【问题讨论】:

    标签: python xml


    【解决方案1】:

    我会使用python的模块os: 我的文件在目录中:/Users/ach/Documents/Data_Science/img/

    版本 1:

    优雅版:

    import os
    DIR_WITH_FILES='/Users/ach/Documents/Data_Science/img'
    list_png=[f for f in sorted(os.listdir(DIR_WITH_FILES)) if (str(f))[-3:] == "png"]
    list_png_with_path=[DIR_WITH_FILES+'/'+str(f) for f in list_png]  
    

    版本 2:

    一步一步:

    code_1:导入os并给出文件所在目录的路径

    import os
    
    print(os.getcwd())
    MY_WORKING_DIRECTORY=os.getcwd()
    !ls
    DIR_WITH_FILES=MY_WORKING_DIRECTORY+'/img/'
    print(DIR_WITH_FILES)
    

    输出_1

    Users/ach/Documents/Data_Science
    img                                notebooks
    /Users/ach/Documents/Data_Science/img/
    

    code_2:列出目录DIR_WITH_FILES=/Users/ach/Documents/Data_Science/img的文件

    files=sorted(os.listdir(DIR_WITH_FILES))
    print(files)
    

    输出_2

    ['fig_0.png', 'fig_describe_target_0.png', 'fig_describe_target_1.png', 'test.txt']
    

    code_3:创建两个带有扩展名的文件名的列表 png => list_png,以及另一个带有文件名的列表及其路径 => list_png_with_path

     list_png=[]
     list_png_with_path=[]
    
     for f in sorted(os.listdir(DIR_WITH_FILES)):
         if (str(f))[-3:] == "png":
            list_png.append(f)
             png_with_path=DIR_WITH_FILES+str(f)
             list_png_with_path.append(png_with_path)
        
     print(list_png)
     print(list_png_with_path)
    

    输出_3

    ['fig_0.png', 'fig_describe_target_0.png', 'fig_describe_target_1.png']
    
    ['/Users/ach/Documents/Data_Science/img/fig_0.png',  '/Users/ach/Documents/Data_Science/img/fig_describe_target_0.png', '/Users/ach/Documents/Data_Science/img/fig_describe_target_1.png']
    

    您可以看到文件'test.txt' 未包含在列表中。

    如果您想过滤多个扩展程序,只需遍历 code_3

    您也可以查看:Get a filtered list of files in a directory

    【讨论】:

      【解决方案2】:

      表达式("*junitReport.xml")"*junitReport.xml" 相同。添加逗号("*junitReport.xml",) 或将其转换为列表["*junitReport.xml"]

      发生的事情是extensions 收到了值"*junitReport.xml",当您循环访问它时,extension 收到了值'*'、'j'、'u'、....

      第一个值“*”匹配所有内容。

      【讨论】:

        猜你喜欢
        • 2010-12-16
        • 2018-06-30
        • 2014-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-31
        • 2020-11-20
        相关资源
        最近更新 更多