python读取文件夹中的所有图片并将图片名逐行写入txt中

x33g5p2x  于2022-07-10 转载在 Python  
字(0.9k)|赞(0)|评价(0)|浏览(619)

读取文件夹下所有文件

  1. # 文件夹路径
  2. img_path = r'E:/workspace/PyCharmProject/dem_feature/dem\512/label'
  3. # txt 保存路径
  4. save_txt_path = r'./images.txt'
  5. # 读取文件夹中的所有文件
  6. imgs = os.listdir(img_path)

过滤:只保留png结尾的图片

  1. # 图片名列表
  2. names = []
  3. # 过滤:只保留png结尾的图片
  4. for img in imgs:
  5. if img.endswith(".png"):
  6. names.append(img)

创建txt文件并逐行写入

  1. txt = open(save_txt_path,'w')
  2. for name in names:
  3. name = name[:-4] # 去掉后缀名.png
  4. txt.write(name + '\n') # 逐行写入图片名,'\n'表示换行
  5. txt.close()

完整代码

  1. """
  2. #-*-coding:utf-8-*-
  3. # @author: wangyu a beginner programmer, striving to be the strongest.
  4. # @date: 2022/7/7 20:25
  5. """
  6. import os
  7. # 文件夹路径
  8. img_path = r'E:/workspace/PyCharmProject/dem_feature/dem/512/label'
  9. # txt 保存路径
  10. save_txt_path = r'./images.txt'
  11. # 读取文件夹中的所有文件
  12. imgs = os.listdir(img_path)
  13. # 图片名列表
  14. names = []
  15. # 过滤:只保留png结尾的图片
  16. for img in imgs:
  17. if img.endswith(".png"):
  18. names.append(img)
  19. txt = open(save_txt_path,'w')
  20. for name in names:
  21. name = name[:-4] # 去掉后缀名.png
  22. txt.write(name + '\n') # 逐行写入图片名,'\n'表示换行
  23. txt.close()

相关文章