python基礎:匹配指定目錄下符合規則的文件,打印文件全路徑

# -*- coding:utf-8 -*-
#遍歷目錄樹
import os,fnmatch

def all_files(root, patterns='*', single_level=False, yield_folder=False):
    # 將模式從字符串中取出放入列表中
    patterns = patterns.split(';')
    for path, subdirs, files in os.walk(root):
        if yield_folder:
            files.extend(subdirs)
        files.sort()
        for fname in files:
            for pt in patterns:
                if fnmatch.fnmatch(fname, pt):
                    yield os.path.join(path, fname)
                    break
        if single_level:
            break
# fnmatch 來檢查文件名匹配模式
# os.path fnmatch os.walk 生成器
thefile=list(all_files(''E:\\projects\\test-log4j\\', '*.class;*.java;*.properties;*.xml'))
for item in thefile:
    print item

上面選了一個java的idea下的test-log4j應用目錄,打印其下面所有的java、class、properties、xml文件全路徑。

E:\projects\py>python traverse.py

E:\projects\test-log4j\pom.xml
E:\projects\test-log4j.idea\compiler.xml
E:\projects\test-log4j.idea\misc.xml
E:\projects\test-log4j.idea\modules.xml
E:\projects\test-log4j.idea\workspace.xml
E:\projects\test-log4j.idea\copyright\profiles_settings.xml
E:\projects\test-log4j.idea\libraries\Maven__log4j_log4j_1_2_17.xml
E:\projects\test-log4j.idea\markdown-navigator\profiles_settings.xml
E:\projects\test-log4j\src\main\java\Main.java
E:\projects\test-log4j\src\main\resources\log4j.properties
E:\projects\test-log4j\src\main\resources\log4j.xml
E:\projects\test-log4j\target\classes\Main.class
E:\projects\test-log4j\target\classes\log4j.properties
E:\projects\test-log4j\target\classes\log4j.xml

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章