如何获取文件的父目录和子目录
问题描述:
我想列出特定文件所属目录的名称。下面是我的文件树的例子:如何获取文件的父目录和子目录
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他们想知道如何获取包含在子目录中的文件的父目录。任何帮助或替代方法将不胜感激。
答
由于Jean-François Fabre和Jjpx对于此解决方案:
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
[蟒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