【发布时间】:2016-11-24 22:52:39
【问题描述】:
我是 Python 的初学者。 我正在尝试使用包含可变深度的测试用例(. 文件)的目录树,例如,test(顶级目录)有 2 个子 test1 和 test 2。 test1 有进一步的分支 t1 和 t2,其中包含 t1.c 和 t2 .c 分别。同样,test2 有 2 个孩子 test21 和 test22。测试 21 有 t3 和 t4 包含 t3.c 和 t4.c 响应。 test22 有 t5 和 t6 有 t5.c 和 t6.c。 我正在尝试搜索 .c 文件,然后使用递归打印其路径。
我得到的错误是代码跟踪器仅通过一个分支,并且没有返回到上一级通过其他分支。请在这里帮助我。
以下是我的代码:
# assume, at no level folders and .c files are present at the same time
import os import fnmatch
# move to test directory
os.chdir('/home/gyadav/test')
# function to create a list of sub directories
def create_subdir_list():
subdirs = os.listdir('.')
len_subdirs = len(subdirs) - 1
# while i != length
for i in range(0, len_subdirs):
# move to next folder
os.chdir(subdirs[i])
print os.getcwd()
subdirs1 = (os.listdir('.'))
print subdirs1
# call function - open thedirectory and check for .c file
open_dir('.')
# definition of check for . c file
def check_for_c():
cfile = fnmatch.filter(os.listdir('.'), '*.c')
# if file found
if len(cfile) != 0:
# save the path
path = os.path.dirname(os.path.abspath(cfile[0]))
print path
os.chdir('..')
print os.getcwd()
else:
create_subdir_list()
def open_dir(name):
check_for_c()
open_dir('.')
【问题讨论】:
-
请删除所有
>。
标签: python recursion tree directory