【问题标题】:python printing the path names of .c files from a directory treepython从目录树打印.c文件的路径名
【发布时间】: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


【解决方案1】:

最好用自己的方式来练习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 文件。

【讨论】:

  • 是的,这绝对是一种更高效的方式。通过您的回答,我很容易得到了想要的结果。不过,您能否建议递归方法中的错误可能是什么?我似乎无法弄清楚。
猜你喜欢
  • 2017-05-04
  • 2019-11-11
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多