Python 如何获取文件的父目录和子目录

Python 如何获取文件的父目录和子目录,python,Python,我尝试列出一个特定文件所属目录的名称。下面是我的文件树的一个示例: 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 dir

我尝试列出一个特定文件所属目录的名称。下面是我的文件树的一个示例:

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
我似乎不知道如何将文件的父目录包含在子目录中。非常感谢您的任何帮助或替代方法。

感谢此解决方案:

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

表示relpath将第一个参数作为目标,第二个参数作为原点。在您的帖子中,您正在将
root
与其自身进行比较,但是您应该执行
relpath(root,root\u文件夹)
并且对于打印,您可以使用
tag.replace(os.path.sep,',')
谢谢!这非常接近。我得到这个
sub-two-a.txt属于topic\u two/子文件夹\u one,topic\u two
。对于子目录打印输出,是否仍要删除
topic\u two/
os.path.basename()
会做一些小动作,谢谢你,@Jean Françoisfab!您的回答和@Jjpx的建议帮助我解决了问题。现在
root
已经包含了从
root\u文件夹到
文件的相对路径。对于更深层次的文件,您最好打印“文件:”,文件“属于”,“,”。加入(root.split(os.path.sep))