我想列出特定文件所属目录的名称。下面是我的文件树的例子:如何获取文件的父目录和子目录
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