想通过python搜索所需要的图片
图片名称中含目录字段是所需的图片
图片所在文件夹,有子文件夹。
通过excel目录搜索图片,将能搜索到的图片复制到新建文件夹。不能搜索到的图片生成新的excel目录。
不能搜索到的图片需生成新的excel目录。
我觉得我应该理解了,我写个
import shutil
import os
import pandas as pd
path1='D:/ZZF/excel1.xlsx' ##原始excel
path11='D:/ZZF/excel2.xlsx' ##剩余的 excel
paht2='D:/质检报告2020/'
path3='D:/ZZF/新建文件夹/' ##移动的目标路径
imgdf=pd.read_excel(path1,sheet_name='Sheet1',header=None)
imgdf.columns=['img']
imgname=list(imgdf.img)
imgname=[i.lower() for i in imgname]
##判断目标文件夹是否存在,如果不存在就新建一个
if not os.path.exists(path3):
os.makedirs(path3)
for root, dirs, files in os.walk(path2): ##遍历所有文件,root 表示目录,dirs 表示文件夹名,files 表示文件
for f in files: ##在文件中循环
if f.lower() in imgname:
shutil.copy(os.path.join(root, f),path3+f)
imgname.remove(f.lower())
pd.DataFrame({'img':imgname}).to_excel(path11,index=0,header=None)
没太理解什么意思,能更详细点吗,
1、'通过excel目录搜索图片' 在什么目录下搜索那些图片
2、‘‘将能搜索到的图片复制到新建文件夹’’ ,新建文件夹目录在哪里,图片又在哪里,
已补充
简单写了下。
注:可能有bug,需要根据实际情况调试下。
操作步骤:
1、把sheet3的文本直接复制粘贴出来放在input.txt里面,
2、修改image_dir = '02/' 为自己图片文件夹的路径
3、运行 python3 main.py
4、输出output.txt即为所求没有的照片,
有的照片都在图片文件夹路径的/new文件夹下
5、将output.txt打开,内容复制粘贴进去excel即可。
代码
main.py
import os, shutil
def file_name_walk(file_dir):
_dirs = []
for root, dirs, files in os.walk(file_dir):
_dirs.append(root)
return _dirs
input_file = 'input.txt'
output_file = 'output.txt'
image_dir = '/home/hyh/Code/myems-reporting-tkl/02/' # 修改成自己的路径,建议不要带中文
_dirs = file_name_walk(image_dir)
if not os.path.exists(image_dir+'new'): # 判断文件夹是否存在
os.mkdir(image_dir+'new')
with open(input_file, "r") as fr:
lines = fr.readlines()
no_images = []
for line in lines:
image = line.replace('\n', '')
flag = False
for _dir in _dirs:
if image.lower() in _dir.lower():
shutil.copy(_dir, image_dir+'new')
flag = True
break
if not flag:
no_images.append(image)
print(no_images)
with open(output_file, "w") as fw:
for image in no_images:
fw.write(image + '\n')
查找目录的范围?
只想给思路,不想写。
1.用pandas将文件名列.tolist()成列表
2.确认top文件夹,就是所有图片肯定都在该文件夹内。os.walk,会得到./文件名.后缀的list。
3.for 2所得的list,spilt(/)取[1]获得文件名.后缀
4.if 文件名在1生成的列表中,那就with open read,然后在指定path with open write
demo
import pandas as pd
import shutil
import os
pic_ls=list(pd.read_excel(【修改成你的excel路径】,sheet_name='sheet3',header=None))
inc_ls=[]
for roots,dirs,files in os.walk('D:\\质检报告2020'):
inc_file=list(filter(lambda x:x in pic_ls,files))
if inc_file:
for each in inc_file:
shutil.copy(roots+'\\'+each,【放置新建文件夹的地方】)
inc_ls+=inc_file
not_inc=list(filter(lambda x:x not in inc_ls,pic_ls))
write_series=pd.Series(not_inc)
not_inc.to_excel(【新的excel路径】,index=False,header=False)
修改以下【】的路径部分