本文實(shí)例為大家分享了python批量復(fù)制圖片到文件夾的具體代碼,供大家參考,具體內(nèi)容如下
直接上代碼:
# -*- coding: utf-8 -*- """ Created on Mon Apr 02 21:03:44 2018 @author: Fsl """ import shutil #這個(gè)庫(kù)復(fù)制文件比較省事 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(): ''' 復(fù)制、重命名、粘貼文件 :return: ''' local_img_name=r'G:\KeTi\OCT\JPEGImages' #指定要復(fù)制的圖片路徑 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()
就這么多,很簡(jiǎn)單。
小編再為大家分享python實(shí)現(xiàn)圖片批量復(fù)制或刪除的代碼,如下
#coding=utf-8 import os import shutil #遞歸復(fù)制文件夾內(nèi)的文件 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): #如果目的路徑不存在該文件就創(chuàng)建空文件,并保持目錄層級(jí)結(jié)構(gòu) if not os.path.exists(targetDir): os.makedirs(targetDir) #如果目的路徑里面不存在某個(gè)文件或者存在那個(gè)同名文件但是文件有殘缺,則復(fù)制,否則跳過(guò) 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) #遍歷某個(gè)目錄及其子目錄下所有文件拷貝到某個(gè)目錄中 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函數(shù)返回一個(gè)三元組 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")
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
