本文实例为大家分享了python批量复制图片到文件夹的具体代码,供大家参考,具体内容如下
直接上代码:
# -*- coding: utf-8 -*-
"""
created on mon apr 02 21:03:44 2018
@author: fsl
"""
import shutil
#这个库复制文件比较省事
def objfilename():
'''
生成文件名列表
:return:
'''
local_file_name_list = r'g:\keti\oct\imagesets\main\test.txt'
#指定名单
obj_name_list = []
for i in open(local_file_name_list,'r'):
obj_name_list.append(i.replace('\n',''))
return obj_name_list
def copy_img():
'''
复制、重命名、粘贴文件
:return:
'''
local_img_name=r'g:\keti\oct\jpegimages'
#指定要复制的图片路径
path = r'g:\keti\oct\data'
#指定存放图片的目录
for i in objfilename():
new_obj_name = i+'.jpg'
shutil.copy(local_img_name+'/'+new_obj_name,path+'/'+new_obj_name)
if __name__ == '__main__':
copy_img()
就这么多,很简单。
小编再为大家分享python实现图片批量复制或删除的代码,如下
#coding=utf-8
import os
import shutil
#递归复制文件夹内的文件
def copyfiles(sourcedir,targetdir):
#忽略某些特定的子文件夹
if sourcedir.find("exceptionfolder")>0:
return
#列出源目录文件和文件夹
for file in os.listdir(sourcedir):
#拼接完整路径
sourcefile = os.path.join(sourcedir,file)
targetfile = os.path.join(targetdir,file)
#如果是文件则处理
if os.path.isfile(sourcefile):
#如果目的路径不存在该文件就创建空文件,并保持目录层级结构
if not os.path.exists(targetdir):
os.makedirs(targetdir)
#如果目的路径里面不存在某个文件或者存在那个同名文件但是文件有残缺,则复制,否则跳过
if not os.path.exists(targetfile) or (os.path.exists(targetfile) and (os.path.getsize(targetfile) != os.path.getsize(sourcefile))):
open(targetfile, "wb").write(open(sourcefile, "rb").read())
print targetfile+" copy succeeded"
#如果是文件夹则递归
if os.path.isdir(sourcefile):
copyfiles(sourcefile, targetfile)
#遍历某个目录及其子目录下所有文件拷贝到某个目录中
def copyfiles2(srcpath,dstpath):
if not os.path.exists(srcpath):
print "src path not exist!"
if not os.path.exists(dstpath):
os.makedirs(dstpath)
#递归遍历文件夹下的文件,用os.walk函数返回一个三元组
for root,dirs,files in os.walk(srcpath):
for eachfile in files:
shutil.copy(os.path.join(root,eachfile),dstpath)
print eachfile+" copy succeeded"
#删除某目录下特定文件
def removefileindir(sourcedir):
for file in os.listdir(sourcedir):
file=os.path.join(sourcedir,file) #必须拼接完整文件名
if os.path.isfile(file) and file.find(".jpg")>0:
os.remove(file)
print file+" remove succeeded"
if __name__ =="__main__":
copyfiles("./dir1","./dir2")
#removefileindir("./dir2")
#copyfiles2("./dir1","./dir2")
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!