如何在python中使用os.walk函数获取完整路径

问题描述 投票:0回答:3

我正在使用os.walk查找目录,但未显示完整路径

代码:

for root, subdirs, files in os.walk(path):
    print(subdirs)

我将系统/值分配给路径。

预期输出:系统/一个/一个

输出:a

现在我可以使用glob.glob,但这列出了符号链接,但我不希望这样

python
3个回答
2
投票
for root, dirnames, fnames in os.walk(path):
    print("I am looking in", root)
    print("These are the subdirectories:")
    for dirname in dirnames:
        print(os.path.join(root, dirname))

    print("These are the filenames:")
    for fname in fnames:
        print(os.path.join(root, fname))

2
投票

引用the documentation

要获取目录路径中文件或目录的完整路径(从顶部开始),请执行os.path.join(dirpath, name)

将它们放在一起,您将得到以下内容:

for root, subdirs, files in os.walk(path):
    for dir in subdirs:
        print(os.path.join(root, dir))

1
投票

这是您应该做的:

import os
for root,subdirs,files in os.walk(path):
    for file in files:
        print(os.path.join(root,file))
© www.soinside.com 2019 - 2024. All rights reserved.