python目录文件的生成

目标:读取某个文件夹中所有JPG格式的图片的名字,并且按照列表的格式保存成TXT文档。为对文件能够进行脚本运行提供一个目录文件。
工具:python3.6,os库,目录下有相同文件名的txt文件。

import os


def ListFilesToTxt(dir,file,wildcard,recursion):
    exts = wildcard.split(" ")
    files = os.listdir(dir)
    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="D:\\抠图\\数据集\\数据集\\coco\\test2017"     #文件路径
  outfile="D:\\抠图\\数据集\\人物\\ming.txt"                     #写入的txt文件名
  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()


Test()

参考别人的代码,进行小幅度更改。

你可能感兴趣的:(python)