如何编写程序以从命令行接受字符串并打印文件夹(也是子文件夹)中与该字符串匹配的所有文件名?
我正在寻找模式匹配。
您可以使用此技术
import os, fnmatch, sys
def all_files(root, patterns='*', single_level=False, yield_folders=False):
# Expand patterns from semicolon-separated string to list
patterns = patterns.split(';')
for path, subdirs, files in os.walk(root):
if yield_folders:
files.extend(subdirs)
files.sort( )
for name in files:
for pattern in patterns:
if fnmatch.fnmatch(name, pattern):
yield os.path.join(path, name)
break
if single_level:
break
user_definedpath, filepattern = sys.argv[1], sys.argv[2]
# Invoking the all_files and putting them into list
#thefiles = list(all_files('/tmp', '*.py;*.htm;*.html'))
thefiles = list(all_files(user_definedpath, filepattern))
print thefiles
现在您可以将这个文件保存为sample.py
say/tmp/abc/sample.py
然后您可以执行为python /tmp/abc/sample.py "/tmp/xyz/" "*.py;*.txt"
import sys, os, operator, re
def filesMatching(pattern, top):
return [f for f in os.listdir(top) if os.path.isfile(os.path.join(top,f)) and re.match(pattern, f)] + reduce (operator.__concat__, [filesMatching (pattern, os.path.join(top,f)) for f in os.listdir (top) if os.path.isdir(os.path.join(top,f))], [])
print (filesMatching (sys.argv[1], sys.argv[2]))