Discuss / Python / 作业

作业

Topic source

only枫树

#1 Created at ... [Delete] [Delete and Lock User]

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 d==filename:
        print(os.path.join(dirpath,d))
        return
    #当前路径下不存在文件,则在子目录下搜索
    if os.path.isdir(d):
        search(filename,os.chdir(os.path.join(dirpath,d)))

only枫树

#2 Created at ... [Delete] [Delete and Lock User]

更正:漏看了包含字符串这个条件 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))

确实如楼上所说,直接用 search(filename, os.path.join(dirpath, d)) 貌似就行了吧,不用os.chdir()就不会改变路径。


  • 1

Reply