2016-04-04 9 views
1

内のすべてのフォルダを通って行く私は、ディレクトリ内のすべてのフォルダを移動したい:は、Python

directory\ 
    folderA\ 
     a.cpp 
    folderB\ 
     b.cpp 
    folderC\ 
     c.cpp 
    folderD\ 
     d.cpp 

フォルダの名前はすべて知られています。 具体的には、a.cppb.cppc.ppd.cppソースファイルのそれぞれのコード行数を数えようとしています。だから、これは私が今まで持っているものである

など folderAの内側に行くと a.cppを読んで、行をカウントし、ディレクトリに戻り、 folderBの内側に行く、 b.cppを読んで、行を数える、

dir = directory_path 
for folder_name in folder_list(): 
    dir = os.path.join(dir, folder_name) 
    with open(dir) as file: 
     source= file.read() 
    c = source.count_lines() 

が、私はPythonの初心者であり、私のアプローチが適切で進歩するかどうかは分かりません。表示されているコード例はすべて喜ばれます!

さらに、ファイルの開閉を処理するので、これらすべての読み取りで処理する必要がありますか、それ以上の処理が必要ですか?with open

答えて

3

私はこのようにそれを行うだろう:

import glob 
import os 

path = 'C:/Users/me/Desktop/' # give the path where all the folders are located 
list_of_folders = ['test1', 'test2'] # give the program a list with all the folders you need 
names = {} # initialize a dict 

for each_folder in list_of_folders: # go through each file from a folder 
    full_path = os.path.join(path, each_folder) # join the path 
    os.chdir(full_path) # change directory to the desired path 

    for each_file in glob.glob('*.cpp'): # self-explanatory 
     with open(each_file) as f: # opens a file - no need to close it 
      names[each_file] = sum(1 for line in f if line.strip()) 

    print(names) 

出力:with質問について

{'file1.cpp': 2, 'file3.cpp': 2, 'file2.cpp': 2} 
{'file1.cpp': 2, 'file3.cpp': 2, 'file2.cpp': 2} 

、あなたはファイルを閉じたりする必要はありませんその他の小切手。あなたは今のように安全でなければなりません。

あなたはfull_pathが誰かとして存在している場合しかし、チェック(あなたは)誤っ(list_of_foldersからフォルダ)

お使いのPCからフォルダを削除する可能性がありますがTrue場合を返しos.path.isdirことにより、これを行うことができますファイルが存在します。

os.path.isdir(full_path)

PSを:私は、Python 3

2

Python 3のos.walk()を使用して、特定のパスのすべてのサブディレクトリとファイルを走査し、各ファイルを開き、ロジックを実行します。 'for'ループを使って歩くことができ、コードを大幅に簡素化できます。

https://docs.python.org/2/library/os.html#os.walk

1

A使用しましたあなたのmanglanoは言った、os.walk()

あなたはフォルダのリストを生成することができます。

[src for src,_,_ in os.walk(sourcedir)] 

ファイルパスのリストを生成できます。

[src+'/'+file for src,dir,files in os.walk(sourcedir) for file in files]