Discuss / Python / 写的递归,却没办法找到子文件夹的文件

写的递归,却没办法找到子文件夹的文件

Topic source

31nm

#1 Created at ... [Delete] [Delete and Lock User]
import os
def find_file(file, cwl):
    #cwl = os.path.abspath(cwl)
    list_of_cwd = [x for x in os.listdir(cwl)]
    print(list_of_cwd)
    for i in list_of_cwd:
        if os.path.isfile(i):
            if file in i:
                print(os.path.abspath(i))
        elif os.path.isdir(i):
            #cwl = os.path.join(cwl, i)
            print(cwl)
            find_file(file, os.path.join(cwl, i))

if __name__ == '__main__':
    find_file('fi', '.')

输出是这样的:

['err.py', 'fileopen.py', 'find_file.py', 'first.py', 'hnss.csv', 'hnss22.txt', 'mydict.py', 'mydict_test.py', 'mydict_test2.py', 'prop.py', 'report.py', 'sources', 'test1.py', 'weatherman.py', 'zoo.py', '__pycache__']
C:\Users\hawsi\py\fileopen.py
C:\Users\hawsi\py\find_file.py
C:\Users\hawsi\py\first.py
.
['daily.py', 'ddfii.txt', 'init.py', 'report.py', 'weekly.py', '__pycache__']
.\sources
['daily.cpython-36.pyc', 'weekly.cpython-36.pyc']
.
['find_file.cpython-36.pyc', 'first.cpython-36.pyc', 'mydict.cpython-35.pyc', 'report.cpython-36.pyc', 'weatherman.cpython-36.pyc', 'zoo.cpython-35.pyc']

求大神指教,为什么我找不到子文件夹里面的文件呢?

你少了return,你写的那行find_file(file, os.path.join(cwl, i))实际上没有运行。

不对,我自己搞糊涂了,不是这个原因……

一堆石

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

我感觉是isfile这个函数的原因,你参考参考这篇博文。 http://blog.csdn.net/qq_28648083/article/details/53233925?locationNum=3&fps=1


  • 1

Reply