代码功能:
读取txt中的每一行,然后匹配某个文件夹中的图片名称,匹配成功的话将该图片复制到一个新的文件夹中。
文件格式如下
----img_res
--000001.jpg
--000002.jpg
--000003.jpg
...
--000018.jpg
----main
--test.txt
--000002
--000004
--000007
--000009
----copy_pic.py
其中img_res文件夹的内容如下:
其中test.txt文档内容如下:
copy_pic.py内容如下:
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 17:10:11 2020
@author: zqq
"""
import os
import shutil
# 读取图片的路径
read_path = "img_res"
# 存放图片的路径
save_path = "img_new"
if not os.path.exists(save_path):
os.mkdir(save_path)
fileType = '.jpg'
num = 0
# 读取并遍历读取txt中的每行
with open('main/test.txt','r') as f:
for name in f:
fileName = name.strip() # 去除末尾的换行
#print(fileName)
#print(type(fileName)) # 查看文件类型
# 读取并遍历文件夹中的图片
for file in os.listdir(read_path):
#print(file)
#print(type(file))
if fileName+fileType == file:
num+=1
shutil.copy(os.path.join(read_path,fileName+fileType),save_path)
print("%s Copy successfully"%(fileName+fileType))
print("Copy complete!")
print("Total pictures copied:",num)
### 测试
# shutil.copy('img_res/000001.jpg',save_path)
# fileName = '000001'
# shutil.copy(os.path.join(read_path,fileName+fileType),save_path)
运行代码后文件格式如下:
----img_res
--000002.jpg
--000004.jpg
--000007.jpg
--000009.jpg
----img_res
--000001.jpg
--000002.jpg
--000003.jpg
...
--000018.jpg
----main
--test.txt
--000002
--000004
--000007
--000009
----copy_pic.py
注:代码还可以优化,比如,我们可以不用将test.txt中每一行和img_res中的图片名进行匹配,而是直接移动。因为我们知道test.txt中的每一行都在img_res中。做匹配比较是为了满足当test.txt中的每一行中不满足在img_res中的条件。
参考:
https://www.cnblogs.com/zangyu/p/5764905.html
https://blog.youkuaiyun.com/weixin_45334587/article/details/104270117