我想列出特定文件所屬目錄的名稱。下面是我的文件樹的例子:如何獲取文件的父目錄和子目錄
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他們想知道如何獲取包含在子目錄中的文件的父目錄。任何幫助或替代方法將不勝感激。
[蟒DOC](https://docs.python.org/3.4/library/os。 path.html#os.path.relpath)表示relpath將第一個參數作爲目標,第二個參數作爲原點。在你的文章中,你正在比較'root',但是你應該'relpath(root,root_folder)' – user1040495
而對於打印,你可以使用'tag.replace(os.path.sep,',')' – user1040495
謝謝!這非常接近。我得到這個'sub-two-a.txt屬於topic_two/subfolder_one,topic_two'。無論如何刪除'topic_two /'的子目錄打印出來? – AldoTheApache