行业知识
Python遍历文件夹包括特定字符的文件名和路径
2026-11-08 22:57:09
来源:互联网转载
Python遍历文件夹包括特定字符的文件名和路径
需���:遍历文件夹和子文件夹,并找出文件名中包含特定字符串 。
()import os import fnmatch def find_files_with_name_pattern(root_dir, pattern): result = [] # 遍历文件夹和子文件夹 for dirpath, dirnames, filenames in os.walk(root_dir): for filename in filenames: if fnmatch.fnmatch(filename, pattern): # 构建文件的完整路径 file_path = os.path.join(dirpath, filename) result.append(file_path) return result # 设置根目录和要匹配的文件名模式 root_dir = "../" # 替换为起始的目录路径 pattern = "*backup*" # 匹配包含的文件名 # 查找文件 files_with_pattern = find_files_with_name_pattern(root_dir, pattern) # 文件名排序files_with_pattern.sort() # 打印结果 for file in files_with_pattern: print(file)()
上一篇:怎么看网页宽度?