Python-读取目录所有文件的文件名,并可定制编号顺序保存到txt文件

import os

def ListFilesToTxt(dir, file, wildcard, recursion):
    exts = wildcard.split(" ")
    files = os.listdir(dir)
    files.sort(key=lambda x: int(x[:-4]))

    for name in files:
        fullname = os.path.join(dir, name)
        if (os.path.isdir(fullname) & recursion):
            ListFilesToTxt(fullname, file, wildcard, recursion)
        else:
            for ext in exts:
                if (name.endswith(ext)):
                    file.write(name + "\n")
                    break


def Test():
    dir = r"C:\Users\87419\Desktop\VAE1\data\trainA"  # 读入
    outfile = "label.txt"  # 写入
    # wildcard = ".jpg .txt .exe .dll .lib"  # 要读取的文件类型
    wildcard = ".jpg"

    file = open(outfile, "w")
    if not file:
        print("cannot open the file %s for writing" % outfile)

    ListFilesToTxt(dir, file, wildcard, 1)

    file.close()

if __name__ == '__main__':
    Test()

https://blog.csdn.net/CVAIDL/article/details/79470096?utm_source=blogxgwz0  mark

猜你喜欢

转载自blog.csdn.net/qq_39938666/article/details/88351535