python3 实现遍历目录与子目录,并抓取.py文件

1
2
3
4
5
6
7
8
9
10
tree test
.
├── subtest1
│   ├── subsubdir
│   │   └── sub.py
│   └── test1.py
├── subtest2
│   └── test2.py
└── subtest3
└── test3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 2. splitext filename to filter

import os

def (dir, suffix):

res = []
for root, directory, files in os.walk(dir):
for filename in files:
name, suf = os.path.splitext(filename)
if suf == suffix:
res.append(os.path.join(root, filename))
return res

for file in getFiles("./", '.py'):
print(file)
# output:
# ./walkdir.py
# ./subtest2/test2.py
# ./subtest3/test3.py
# ./subtest1/test1.py
# ./subtest1/subsubdir/sub.py