2016-08-12 174 views
2

我想列出特定文件所屬目錄的名稱。下面是我的文件樹的例子:如何獲取文件的父目錄和子目錄

root_folder 
├── topic_one 
│   ├── one-a.txt 
│   └── one-b.txt 
└── topic_two 
    ├── subfolder_one 
    │   └── sub-two-a.txt 
    ├── two-a.txt 
    └── two-b.txt 

理想的情況下,想什麼,我已經打印出來的是:

"File: file_name belongs in parent directory" 
"File: file_name belongs in sub directory, parent directory" 

我寫這個劇本:

for root, dirs, files in os.walk(root_folder): 

# removes hidden files and dirs 
    files = [f for f in files if not f[0] == '.'] 
    dirs = [d for d in dirs if not d[0] == '.'] 

    if files: 
     tag = os.path.relpath(root, os.path.dirname(root)) 
     for file in files: 
      print file, "belongs in", tag 

這給我這個輸出:

one-a.txt belongs in topic_one 
one-b.txt belongs in topic_one 
two-a.txt belongs in topic_two 
two-b.txt belongs in topic_two 
sub-two-a.txt belongs in subfolder_one 

我不能se他們想知道如何獲取包含在子目錄中的文件的父目錄。任何幫助或替代方法將不勝感激。

+0

[蟒DOC](https://docs.python.org/3.4/library/os。 path.html#os.path.relpath)表示relpath將第一個參數作爲目標,第二個參數作爲原點。在你的文章中,你正在比較'root',但是你應該'relpath(root,root_folder)' – user1040495

+0

而對於打印,你可以使用'tag.replace(os.path.sep,',')' – user1040495

+0

謝謝!這非常接近。我得到這個'sub-two-a.txt屬於topic_two/subfolder_one,topic_two'。無論如何刪除'topic_two /'的子目錄打印出來? – AldoTheApache

回答

0

由於Jean-François FabreJjpx對於此解決方案:

for root, dirs, files in os.walk(root_folder): 

    # removes hidden files and dirs 
    files = [f for f in files if not f[0] == '.'] 
    dirs = [d for d in dirs if not d[0] == '.'] 

    if files: 
     tag = os.path.relpath(root, root_folder) 

     for file in files: 
      tag_parent = os.path.dirname(tag) 

      sub_folder = os.path.basename(tag) 

      print "File:",file,"belongs in",tag_parent, sub_folder if sub_folder else "" 

打印出:

File: one-a.txt belongs in topic_one 
File: one-b.txt belongs in topic_one 
File: two-a.txt belongs in topic_two 
File: two-b.txt belongs in topic_two 
File: sub-two-a.txt belongs in topic_two subfolder_one 
+0

如今'root'已經包含了從'root_folder'到'file'的相對路徑。對於更深的文件,你最好的選擇是「打印」文件:「,file」屬於「,」,「。join(root.split(os.path.sep))' – user1040495

+0

如果你的答案解決了你的問題,公認 – user1040495