2013-01-06 39 views
6

Tôi có cấu trúc tập tin như vậy:os.walk lấy tên thư mục

d:\temp\random1\index.html 
d:\temp\random2\index.html 
d:\temp\random3\index.html 

và tôi muốn để có được đường dẫn để liệt kê trong python. Vì vậy, đầu ra sẽ là:

files = ['path': 'd:\temp\random1\index.html', 'directory': 'random1'] 

Tôi đang sử dụng mã như:

files = [] 
for dirpath, dirnames, filenames in os.walk('D:\\temp'): 
    for fname in filenames: 
     if fname.endswith(".md"): 
      path = os.path.join(dirpath,fname) 
      files.append({'path':path,'directory': dirpath}) 

nhưng tôi không thể tìm ra cách để có được thư mục values.All tôi nhận được với mã này là:

files = ['path': 'd:\temp\random1\index.html', 'directory': 'd:\temp\random1\'] 

Làm thế nào để lấy thư mục mà không có một số hack bẩn?

Trả lời

9

Hãy thử

dirname = dirpath.split(os.path.sep)[-1] 
Các vấn đề liên quan