为什么os.listdir返回错误的结果?

时间:2019-06-17 11:05:47

标签: python python-2.7

我正在尝试打印目录中所有成员的完整路径,但是结果不正确。

import sys
import os
from os.path import abspath

test_directory = abspath(r'D:\Python\test')
print test_directory

for sub_directory in os.listdir(test_directory):
    print abspath(sub_directory)

调用脚本将给出以下内容:

D:\Python\test
D:\Python\one
D:\Python\three
D:\Python\two

实际上,我的目录结构实际上是这样的:

D:\Python\test
D:\Python\test\one
D:\Python\test\two
D:\Python\test\three

1 个答案:

答案 0 :(得分:0)

尝试使用os.walk

path_collection = []

for dirpath, dirnams, filenames in os.walk(r'D:\Python\test'):
    for file in filenames:
        fullpath = os.path.join(dirpath, file)
        path_collection.append(fullpath)
for i in path_collection:
    print(i)