# -*- coding:utf-8 -*-#遍历目录树import os,fnmatchdef 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
The test-log4j application directory under the idea of Java is selected to print all the Java, class, properties, and XML file full paths below it.
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
Python basics: Match rules-compliant files in the specified directory, print file full path