本文實例為大家分享了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")
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

