Learn more pyhton 3 in hard way
ex6.py
代码:https://github.com/theguyisnoone/impthw/blob/master/ex6.py
有几个版本 可以看history 进行对比
相关资料:https://docs.python.org/3/library/pathlib.html
思路:
1.调查 pathlib 在python doc 上
2.用argv 的方法 通过 name 找到文件
会话代码: ex6.py . -n “*.txt” ### " . ”是当前路径的意思
3.用argparse 只实现name -n 查找
4.add type查找 d可以了 f不可以查出来
代码 ex6.py . -t d
ex6.py . -t f 报错
5.修复这个bug
将start_path.rglob(args.name)改成 星号
```
start_path.rglob(‘*’)
```
为了保证两个d,f都可以使用 该成
start_path.rglob(args.name or ‘*’ )
原因在于
星号的范围大
6.改成def()
#put all the things into def()
from pathlib import Path
import argparse
import sys
def parse_args():
parser=argparse.ArgumentParser()
parser.add_argument('start',type=str,nargs=1)
parser.add_argument('-n','--name',type=str)
parser.add_argument('-t','--type',type=str)
return parser.parse_args()
def find_file(args):
start_path=Path(args.start[0])
if args.name and not args.type:
name_find(start_path,args)
elif args.type:
type_find(start_path,args)
else:
print("please print -n or -t")
sys.exit(1)
def name_find(start_path,args):
for f in start_path.rglob(args.name):
print(f)
def type_find(start_path,args):
if args.type not in ['d','f']:
print("unknown type:{args.type}")
sys.exit(1)
for f in start_path.rglob('*' or args.name):
if args.type== "d" and f.is_dir():
print(f)
elif args.type== "f" and f.is_file():
print(f)
find_file(parse_args())
运行截图: