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 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

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

最佳答案

感谢 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

关于python - 如何获取文件的父目录和子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38926949/

相关文章:

Python 刷新 sqlite3 连接以检索最新值

python - 将 float 划分到桶中

python - 当 DEBUG=False 时 Flask mail 不发送邮件

Python请求不重定向

python - 为什么Python多处理管理器会产生线程锁?

python - 使用 Python 更新表时 Sqlite 出错

python - 将 json 从 url 拉入数据帧错误

python - python覆盖模块可以有条件地忽略单元测试中的行吗?

python - 线程执行完毕后执行函数

python - 规范化 numpy 中的列