我正在尝试列出特定文件所属的目录名称。下面是我的文件树的一个例子:
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 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
关于python - 如何获取文件的父目录和子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38926949/