用python列出文件名时出现问题

时间:2019-03-05 14:22:32

标签: python python-3.x

我可以使用较低的代码获取python 2.7中具有特定扩展名的文件列表

import os

def discoverFiles(startpath):
    extensions = [
        'ext'
        ]

    for dirpath, dirs, files in os.walk(startpath):
        for i in files:
            absolute_path = os.path.abspath(os.path.join(dirpath, i))
            ext = absolute_path.split('.')[-1]
            if ext in extensions:
                yield absolute_path

n_files = discoverFiles("D:\\") # DriveName For Search

for i in n_files:
    print(i)

但是上面的代码在Python 3中不起作用
我需要上面的代码
请帮助我解决Python 3中的问题

1 个答案:

答案 0 :(得分:0)

尝试一下:

import os

def discoverFiles(startpath):
    extensions = [
        'ext'
        ]

    F = os.listdir(startpath)

    for i in F:
        absolute_path = os.path.abspath(os.path.join(startpath, i))
        ext = absolute_path.split('.')[-1]
        if ext in extensions:
            yield (absolute_path)


n_files = discoverFiles("D:\\") # DriveName For Search

for i in n_files:
    print(i)