Find cmd with python programing python at page320
Unix find cmd:
find . -name "*.py " -print -exec fgrep popen{}\;
from glob import glob
import os def findWithExt(type):
for file in glob(type):
if 'xlian7164584' in open(file).read():
print(file)
print('current directory is %s' % os.path.abspath('.')) ext='*.*'
findWithExt(ext)
find cmd:
"""
return all files matching a filename patten at and below a root directory; custom version of the now dreprecated find modelue in the standard lib:
imprt as "Tools.find" like original ,but uses os.walk loop,has no support for pruning subdires,and
is runnable as top-level script; find() is a generator that uses the os.walk() generator to yield just
mathing filenames:use findlist() to forse result list generation;
"""
import fnmatch
from glob import glob
import os def find(pattern,startdir=os.curdir):
for (thisDir,subHere,filesHere) in os.walk(startdir):
for name in subHere +filesHere:
if fnmatch.fnmatch(name,pattern):
fullpath = os.path.join(thisDir,name)
yield fullpath def findlist(pattern,startdir=os.curdir,dosort=False):
matches = list(find(pattern,startdir))
if dosort:
mathches.sort()
return matches def findWithExt(type):
for file in glob(type):
if 'xlian7164584' in open(file).read():
print(file)
print('current directory is %s' % os.path.abspath('.')) #ext='*.*'
#findWithExt(ext) if __name__ =='__main__':
import sys
namepattern,startdir = sys.argv[1],sys.argv[2]
for name in find(namepattern,startdir):
print(name)