作业
Topic source更正:漏看了包含字符串这个条件 import os
def search(filename,dirpath=None): if dirpath==None: dirpath=os.path.abspath('.')#当前绝对路径
for d in os.listdir('.'):#搜索所有文件及目录
#当前路径下的文件存在,则输出路径
if os.path.isfile(d) and filename in d:
print(os.path.join(dirpath,d))
#当前路径下不存在文件,则在子目录下搜索
if os.path.isdir(d):
#print(os.path.join(dirpath,d))
search(filename,os.chdir(os.path.join(dirpath,d)))
return
结果:
>>> search('test')
D:\廖雪峰python2\mydict_test.py
D:\廖雪峰python2\testdir\test.txt
D:\廖雪峰python2\testdir\testdir2\test2.txt
第一层: 文件夹dir_a , 文件file_a 第二层: 文件file_b , 文件夹 dir_b 第三层: 文件file_c
在第一层,当先遇到文件夹dir_a时,进入第二层的search,注意此时已执行os.chdir(dir_a),当前路径已是 /dir_a 当子层找完,回到第一层的file_a时,判断 os.path.isfile(d)结果是false了,所以file_a就算符合要求,也不会被抓到:
if os.path.isdir(d): #print(os.path.join(dirpath,d)) search(filename,os.chdir(os.path.join(dirpath,d))
- 1
only枫树
import os
def search(filename,dirpath=None):