python:search()递归不执行

Berumottox 2016-10-20 07:42:02

import os

list_result = os.listdir('.')


def search(list_result_copy):
for now in list_result_copy:
if os.path.isfile(now): # file in current directory
print os.path.join(os.path.abspath('.'), now)

if os.path.isdir(now): # directory in current directory
direction = os.listdir(os.path.join(os.path.abspath('.'), now))
search(direction) #就是这里,我想要递归输出所有子目录文件,但是这里压根儿不执行


if __name__ == '__main__':
search(list_result)
...全文
212 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
sblsp 2016-10-21
  • 打赏
  • 举报
回复
在def下面加一行os.chdir(list_result_copy)
xSeeker~ 2016-10-20
  • 打赏
  • 举报
回复
这个问题出在工作目录上 比如说你的工作目录是C:\A,下面有个子目录B,里面有个c.txt 递归到B目录时,实际上的工作目录还是A ,所以判断c.txt是不是文件时,实际上判断的是C:\A\c.txt是不是文件,显然不存在所以就不会打印 我做了个简单的修改
def search(list_result_copy):
    for now in list_result_copy:
        temppath  = os.path.join(os.path.abspath('.'), now)
        if os.path.isfile(temppath):     # file in current directory
            print temppath
 
        if os.path.isdir(temppath):      # directory in current directory
            os.chdir(temppath)
            direction = os.listdir(temppath)
            search(direction)
            os.chdir("..")

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧