Python将多个文件夹中的图片复制到一个文件夹

copy_imgs_to_dir

代码如下:

import os		#专门用于文件处理
import sys        #system系统处理文件
filedir = os.path.dirname(sys.argv[0])      #获取脚本所在目录   sys.argv[0]表示获取脚本的位置
os.chdir(filedir)       #将脚本所在的目录设置为工作目录
wdir = os.getcwd()        #.getcwd() 可以直接输出
print('当前工作目录:{}\n'.format(wdir))      #打印当前工作目录  输出格式一定要用.format()

import shutil   #高级文档处理

image_dir = 'Images_Repo'        
if not os.path.exists(image_dir):   #检测是否存在image_dir文件夹
        os.mkdir(image_dir)        #创建image_dir文件夹

specified_id = 1            
files = os.listdir(image_dir)
file_idxs = [int(file.split('.')[0]) for file in files]
idx = max(file_idxs) if len(file_idxs) != 0 else 1
idx = max(idx+1, specified_id)

f = open(image_dir +'_info.txt', 'a+')
f.seek(0,0)  #移动到文件头
lines = f.readlines()
print(len(lines))
f.seek(0,2)  #移动到文件尾
existed_img = [os.path.basename(line.split(' ')[0]) for line in lines]    
i, j = 0, 0
for parent, dirs, files in os.walk('DATA'):         #浏览整个DATA文件夹 
	parent_base = os.path.basename(parent)         #parent指的是包含脚本的文件夹
	if ('Picture' in parent_base):                  #每次只能处理一个,要么处理文件夹,要么处理文档
		for file in files:
			if file not in existed_img:
				file_ext = file.split('.')[-1]
				new_name = str(idx).zfill(8) + '.' + file_ext
				image_src = os.path.join( parent, file)          #os.path.join()函数用于路径拼接文件路径,例如:parent/***/file
				image_dst = os.path.join( image_dir, new_name)   
				if not os.path.exists(image_dst):    #os.path.exists() 判断文件是否存在
					shutil.copy(image_src, image_dst)     #将老文件复制到新文件中,老文件-->新文件
					idx += 1
					j += 1
					new_line = image_src + '   ------>   ' +image_dst +'\n'
					f.write(new_line)
					print('本次复制了文件{:25s}到文件{:25s}'.format(file, new_name))     #最大的特点就是不用理会数据类型的问题
			else:
				i += 1
				print('文件{:25s}此前已经被复制'.format(file))
f.close()
print('本次跳过了{:6d}个此前已被复制的文件'.format(i))
print('本次复制了{:6d}个文件'.format(j))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RNG_uzi_

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值