《Python编程》笔记专栏现以开源到Gitee,其中包含我编写的示例程序文件和官方示例程序文件,以及md形式的笔记,欢迎各位给个Star。
搜索目录树
开启自己的find
模块
示例:my_PP4E/tools/find.py
#!/usr/bin/env python
"""
##############################################################################
用法:./find.py 'pattern' dirpath
返回某个根目录及其子目录下所有匹配某个文件名模式的文件;
find()是一个生成器,利用os.walk()生成器产生匹配的文件名,可使用findlist强制生成结果列表。
##############################################################################
"""
import os
import sys
import fnmatch
DOSORT = False
STARTDIR = os.curdir
def find(pattern, startdir=STARTDIR):
for thisdir, subdirs, files in os.walk(startdir):
for name in (subdirs + files):
if fnmatch.fnmatch(name, pattern):
fp = os.path.join(thisdir, name)
yield fp
def findlist(pattern, startdir=STARTDIR, dosort=DOSORT):
matches = find(pattern, startdir)
if dosort:
matches.sort()
return matches
def command():
pattern, startdir = sys.argv[1:3]
print('pattern ->', pattern, 'startdir ->', startdir)
for match in find(pattern, startdir):
print(match)
if __name__ == '__main__':
command()
运行:find.py
$ ./find.py '?[abc]*.py' ..
pattern -> ?[abc]*.py startdir -> ..
../echo.py
../launchmodes.py
../system/echo_env.py
../system/make_words.py
../system/scan_file.py
fnmatch
模块
这个模块支持模式名称字符串中使用常用操作符:
*
用来匹配任意数量的字符;?
用来匹配单个字符;[...]
用来匹配方括号内的任意字符,[!...]
用来匹配除过方括号内的字符以外的任意字符。
清理字节码文件
示例:cleanpyc.py
#!/usr/bin/env python
"""
##############################################################################
用法:./cleanpyc rootdir [-f(findonly)]
删除目录树中所有.pyc字节码文件:如果给出命令行参数则将其视为根目录,否则将当前工作目录作为根
目录。
##############################################################################
"""
import find
import sys
import os
FINDONLY = False
ROOTDIR = os.getcwd
def cleanpyc(rootdir=ROOTDIR, findonly=FINDONLY):
print('rootdir ->', rootdir, 'findonly ->', findonly)
found = removed = 0
for pyc in find.find('*.pyc', rootdir):
found += 1
print(pyc)
if not findonly:
try:
os.remove(pyc)
except Exception:
print(
'*' * 4, '删除失败:', pyc,
sys.exc_info()[0], sys.exc_info()[1]
)
else:
removed += 1
print('发现了', found, '个pyc文件,删除了', removed, '个。')
def command(rootdir=ROOTDIR, findonly=FINDONLY):
rootdir = sys.argv[1] if len(sys.argv) > 1 else rootdir
findonly = '-f' in sys.argv
cleanpyc(rootdir, findonly)
if __name__ == '__main__':
command()
运行:cleanpyc.py
my_PP4E/tools$ ./cleanpyc.py .. -f
rootdir -> .. findonly -> True
../tools/__pycache__/find.cpython-37.pyc
发现了 1 个pyc文件,删除了 0 个。
my_PP4E/tools$ ./cleanpyc.py ..
rootdir -> .. findonly -> False
../tools/__pycache__/find.cpython-37.pyc
发现了 1 个pyc文件,删除了 1 个。
Python目录树搜索工具
示例:searchall.py
#!/usr/bin/env python
"""
##############################################################################
用法:./searchall.py dir string [-l(list only)]
搜索指定的目录及其子目录下所有含有指定字符串的文件;首先利用os.walk接口而不是find.find来收
集文件名;类似于find.find('*')的每个返回结果调用visitfile。
##############################################################################
"""
import os
import sys
LISTONLY = False
TEXTEXTS = ['.py', '.pyw', '.txt', '.c', '.cpp', '.h']
def searcher(startdir, searchkey, listonly=LISTONLY):
global fcount, vcount
fcount = vcount = 0
for thisdir, subsdir, files in os.walk(startdir):
for fn in files:
fp = os.path.join(thisdir, fn)
visitfile(fp, searchkey, listonly)
def visitfile(fpath, searchkey, listonly=LISTONLY, textexts=TEXTEXTS):
global fcount, vcount
print(vcount + 1, '->', fpath)
try:
if not listonly:
if os.path.splitext(fpath)[1] not in textexts:
print('跳过:', fpath)
elif searchkey in open(fpath).read():
input('{} 中有字符串 {}'.format(fpath, searchkey))
fcount += 1
except Exception:
print('失败:', fpath, sys.exc_info()[0], sys.exc_info()[1])
vcount += 1
def command(listonly=LISTONLY):
searcher(sys.argv[1], sys.argv[2], '-l' in sys.argv)
print('访问了', vcount, '个文件,匹配了', fcount, '个。')
if __name__ == '__main__':
command()
运行:searchall.py
my_PP4E/tools$ ./searchall.py . os.walk
1 -> ./cleanpyc.py
2 -> ./find.py
./find.py 中有字符串 os.walk
3 -> ./searchall.py
./searchall.py 中有字符串 os.walk
访问了 3 个文件,匹配了 2 个。
my_PP4E/tools$ ./searchall.py . os.walk -l
1 -> ./cleanpyc.py
2 -> ./find.py
3 -> ./searchall.py
访问了 3 个文件,匹配了 0 个。
———————————————————————————————————————————
😃 学完博客后,是不是有所启发呢?如果对此还有疑问,欢迎在评论区留言哦。
如果还想了解更多的信息,欢迎大佬们关注我哦,也可以查看我的个人博客网站BeacherHou。