2016-07-21 8 views
1

私はPythonの初心者です。 私はテストケース(。ファイル)を可変深度に含むディレクトリツリーを使って作業しようとしています。たとえばtest(トップディレクトリ)には2つの子test1とtest2があります。test1にはさらにt1.cとt1.cを含むt1とt2があります。 t2.cとなる。同様に、test2には2人の子test21とtest22があります。テスト21は、t3.cおよびt4.cを含むt3およびt4を有する。 test22はt5とt6を持ち、t5.cとt6.c. .cファイルを検索し、再帰を使用してそのパスを印刷しようとしています。pythonディレクトリツリーから.cファイルのパス名を出力する

私が得ているエラーは、コードが1つのブランチだけを追跡し、他のブランチを通過するために前のレベルに戻ることではないということです。ここで私を助けてください。続き

は私のコードです:

# 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('.') 
+1

'>'をすべて削除してください。 – erip

答えて

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ファイルがリストされます。

+0

はい、これは間違いなくより効率的な方法です。私はあなたの答えで非常に簡単に目的の結果を得ました。 再帰メソッドでエラーが発生する可能性がありますか?私はそれを把握していないようだ。 – Garima

関連する問題