2014-12-06 125 views
0

你好我正在嘗試編寫一個python腳本,它可以查看目錄和子目錄,並提取文件名和擴展名,並將它們列在文件中。感謝您的時間。 例Outputneeded:Python打印目錄和子目錄中的文件名和擴展

Artist 
Album name 
    song.mp3 
    song.wav 
    song.aiff 

的文件存儲爲藝術家,專輯{可能還有很多在這裏},

我目前正在與啓動此{每張專輯}歌曲:

import os 

for dirname, dirnames, filenames in os.walk('.'): 

    for subdirname in dirnames: 
     print os.path.join(dirname, subdirname) 


    for filename in filenames: 
     print os.path.join(dirname, filename) 
+0

只是先打開一個文件,並隨時寫 – 2014-12-06 19:12:33

回答

0

您可以通過計算基本目錄中的路徑分隔符來跟蹤您沿樹的下方多遠。

import os 

def scan_this(path): 
    path = os.path.abspath(path) 
    sep_count = path.count(os.path.sep) + 1 

    for root, dirnames, filenames in os.walk(path): 
     nest_count = root.count(os.path.sep) - sep_count 
     if nest_count <= 1: 
      print '%s%s' % (' ' * nest_count, os.path.basename(root)) 
      if nest_count == 1: 
       for f in filenames: 
        print '%s%s' % (' ' * (nest_count + 1), f) 

scan_this('.') 
相關問題