python3 遍历文件下的所有文件

2019-11-26 14:01:04 浏览数 (1)

代码语言:javascript复制
import os


def img_list(work_dir):
    mlist = []
    for parent, dirnames, filenames in os.walk(work_dir, followlinks=True):
        for filename in filenames:
            file_path = os.path.join(parent, filename)
            mlist.append(file_path)
    dicts = {}
    for ii in mlist:
        m1 = ii.split("\")[-1]
        m2 = ii.split("\")[-2]
        dicts[m1] = m2
    return dicts


if __name__ == '__main__':
    work_dir = 'C:/Users/admin/Desktop/dfs/3/PictureCollector/images'
    # work_dir = '/home/lhadmin/lg/images'

    print(img_list(work_dir))

运行结果:

{'1.jpg': '0', '2.jpg': '0', '3.jpg': '0', '4.jpg': '0', '5.jpg': '0', '6.jpg': '0', '10.jpg': '1', '11.jpg': '1', '12.jpg': '1', '7.jpg': '1', '8.jpg': '1', '9.jpg': '1', '111.jpg': '2', '22.jpg': '2', '33.jpg': '2', '44.jpg': '2'}

0 人点赞