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

时间:2016-08-12 21:51:10

标签: 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 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

我似乎无法弄清楚如何在子目录中获取该文件的父目录。任何帮助或替代方法将不胜感激。

1 个答案:

答案 0 :(得分: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