实现图片文件的复制

1、定义一个函数,接受两个参数,第一个参数是原始图片文件,第二个参数是复制到的路径
def copy_image(source_file,target_path):
# 实现图片文件的复制

解答:

import os
import shutil

def copy_image(source_file,target_path):
#返回源文件夹的列表
source_list = os.listdir(source_file)
#生成新文件夹名
name ='class'
new_dir_name = os.path.join(target_path,name)
#创建新文件夹
if not os.path.exists(new_dir_name):
os.makedirs(new_dir_name)
for file in source_list:
file = os.path.join(source_file,file)
# 拷贝文件夹下的所有图片
if os.path.isfile(file):
if (file.find(".jpg") > 0 or file.find(".png") > 0 or file.find(".jpeg") > 0 or file.find(".bmp") > 0) :
shutil.copy(file,new_dir_name)
print(new_dir_name + '/'+file + ' copy sucess'+' ')

return True
old_path = 'F:/old_file' #这个根据实际情况自己修改属于自己的路径
new_path = 'F:/new_file/'#这个根据实际情况自己修改属于自己的路径

try:
r = copy_image(old_path,new_path)
except Exception as e:
print(e)
finally:
print("拷贝结束!")
原文地址:https://www.cnblogs.com/zbligang/p/10413518.html