2016-08-08 8 views
0

私はmyscript.pyという名前のPythonプログラムを用意しています。これは提供されたパスのファイルとフォルダのリストを私に与えます。pythonでフォルダ名とファイル名を取得する方法

import os 
import sys 

def get_files_in_directory(path): 
    for root, dirs, files in os.walk(path): 
     print(root) 
     print(dirs) 
     print(files) 
path=sys.argv[1] 
get_files_in_directory(path) 

私が提供するパスはD:\Python\TESTであり、あなたが以下に出力して見ることができるよう、その中にいくつかのフォルダとサブフォルダがあります。

C:\Python34>python myscript.py "D:\Python\Test" 
D:\Python\Test 
['D1', 'D2'] 
[] 
D:\Python\Test\D1 
['SD1', 'SD2', 'SD3'] 
[] 
D:\Python\Test\D1\SD1 
[] 
['f1.bat', 'f2.bat', 'f3.bat'] 
D:\Python\Test\D1\SD2 
[] 
['f1.bat'] 
D:\Python\Test\D1\SD3 
[] 
['f1.bat', 'f2.bat'] 
D:\Python\Test\D2 
['SD1', 'SD2'] 
[] 
D:\Python\Test\D2\SD1 
[] 
['f1.bat', 'f2.bat'] 
D:\Python\Test\D2\SD2 
[] 
['f1.bat'] 

私は出力をこのように取得する必要があります:

D1-SD1-f1.bat 
D1-SD1-f2.bat 
D1-SD1-f3.bat 
D1-SD2-f1.bat 
D1-SD3-f1.bat 
D1-SD3-f2.bat 
D2-SD1-f1.bat 
D2-SD1-f2.bat 
D2-SD2-f1.bat 

どのようにすればこのように出力されますか(ここのディレクトリ構造は一例に過ぎません。プログラムは任意のパスに対して柔軟である必要があります)。どのように私はこれを行うのですか? これにはosコマンドがありますか?あなたは私がこれを解決するのを助けてくれますか? (追加情報:私はPython3.4を使用しています)

答えて

1

代わりglobモジュールを使用して試みることができる:

import glob 
glob.glob('D:\Python\Test\D1\*\*\*.bat') 

それとも、単にファイル名

import os 
import glob 
[os.path.basename(x) for x in glob.glob('D:\Python\Test\D1\*\*\*.bat')] 
0

はあなたが望む結果を得るために取得するには次のようにすることができます。

def get_files_in_directory(path): 
    # Get the root dir (in your case: test) 
    rootDir = path.split('\\')[-1] 

    # Walk through all subfolder/files 
    for root, subfolder, fileList in os.walk(path): 
     for file in fileList: 
      # Skip empty dirs 
      if file != '': 
       # Get the full path of the file 
       fullPath = os.path.join(root,file) 

       # Split the path and the file (May do this one and the step above in one go 
       path, file = os.path.split(fullPath) 

       # For each subfolder in the path (in REVERSE order) 
       subfolders = [] 
       for subfolder in path.split('\\')[::-1]: 

        # As long as it isn't the root dir, append it to the subfolders list 
        if subfolder == rootDir: 
         break 
        subfolders.append(subfolder) 

       # Print the list of subfolders (joined by '-') 
       # + '-' + file 
       print('{}-{}'.format('-'.join(subfolders), file)) 

path=sys.argv[1] 
get_files_in_directory(path) 

私のテストフォルダ:

SD1-D1-f1.bat 
SD1-D1-f2.bat 
SD2-D1-f1.bat 
SD3-D1-f1.bat 
SD3-D1-f2.bat 

これは最善の方法ではありませんが、必要なものが得られます。

+0

ありがとうございました。その本当に役に立ちました –

+1

@ SushinK.Kumar:あなたは古いコメントを追加するのではなく、これを受け入れるべきでした。 – usr2564301

関連する問題