我是Python的初学者。
我正在尝试使用包含深度可变的测试用例(。文件)的目录树,例如,test(顶层目录)具有2个子test1和test2。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。但是有效的方法是:

>>> PATH = '/home/sijan/Desktop/'
>>> import os
>>> from glob import glob
>>> result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.py'))]


它将在给定路径内列出文件夹中的所有.py文件。

关于python - python从目录树中打印.c文件的路径名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38502657/

10-09 08:18
查看更多