用python3分别写出一个类似find和grep功能的函数? 200
例如find-namea.txt就能从所有文件中找到grep‘‘a’’a.txt就能在a.txt中找出所有的afind-i要不区分大小写和grep-i,-n,-r都与原来...
例如 find -name a.txt 就能从所有文件中找到
grep ‘‘a’’ a.txt 就能在a.txt中找出所有的a
find -i 要不区分大小写 和 grep -i ,-n,-r 都与原来的功能一样 展开
grep ‘‘a’’ a.txt 就能在a.txt中找出所有的a
find -i 要不区分大小写 和 grep -i ,-n,-r 都与原来的功能一样 展开
展开全部
grep用的少,不熟悉,给个find的你参考一下吧
#!/usr/bin/env python3.6
import os
import sys
def find(args=sys.argv):
ignore = '-i' in args
dirname = '.' if args[1].startswith('-') else args[1]
fname = args[args.index('-name')+1].strip('"\'')
for r, ds, fs in os.walk(dirname):
for fn in fs:
if fn == fname or (ignore and fn.lower() == fname.lower()):
print(os.path.join(r, fn))
def main():
find()
if __name__ == '__main__':
main()
更多追问追答
追问
但他显示这样啊
Traceback (most recent call last):
File "/Users/liuzhenyu/Documents/Untitled.py", line 19, in
main()
File "/Users/liuzhenyu/Documents/Untitled.py", line 16, in main
find()
File "/Users/liuzhenyu/Documents/Untitled.py", line 8, in find
dirname = '.' if args[1].startswith('-') else args[1]
IndexError: list index out of range
>>>
追答
#!/usr/bin/env python3.6
import os
import sys
def find(args=sys.argv):
ignore = '-i' in args
try:
dirname = '.' if args[1].startswith('-') else args[1]
fname = args[args.index('-name')+1].strip('"\'')
except IndexError:
print(f'Usage:\n{" "*4}python3 {args[0]} -name a.txt')
return
for r, ds, fs in os.walk(dirname):
for fn in fs:
if fn == fname or (ignore and fn.lower() == fname.lower()):
print(os.path.join(r, fn))
def main():
find()
if __name__ == '__main__':
main()
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询