python指令碼——將同一個資料夾下的相同檔名的不同檔案分開
阿新 • • 發佈:2019-02-05
需求:一個資料夾下有相同檔名的兩種格式的檔案,且數量相等,我的兩種檔案格式是:jpg和tif.rbox.txt,想要把這兩種檔案分別放到兩個資料夾裡面
例如:將789資料夾下的兩種檔案分別放到456資料夾和000資料夾下(原來的456資料夾和000資料夾是空的)
程式碼如下:
# -*- coding: utf-8 -*- import time import os import shutil def readFilename(path, allfile): filelist = os.listdir(path) for filename in filelist: filepath = os.path.join(path, filename) if os.path.isdir(filepath): readFilename(filepath, allfile) else: allfile.append(filepath) return allfile def mycopyfile(srcfile,dstfile): if not os.path.isfile(srcfile): print "%s not exist!"%(srcfile) else: fpath,fname=os.path.split(dstfile) #分離檔名和路徑 if not os.path.exists(fpath): os.makedirs(fpath) #建立路徑 shutil.copyfile(srcfile,dstfile) #複製檔案 print "copy %s -> %s"%( srcfile,dstfile) if __name__ == '__main__': path1="/Users/sunny/Desktop/789/" path2="/Users/sunny/Desktop/456/" path3="/Users/sunny/Desktop/000/" allfile1=[] allfile1=readFilename(path1,allfile1) allname1=[] for name in allfile1: print name t=name.split(".")[0].split("/")[-1] print t allname1.append(t) print allname1 allname2=list(set(allname1)) print allname2 for ns in allname2: srcfile=path1+str(ns)+'.jpg' dstfile=path3+str(ns)+'.jpg' mycopyfile(srcfile,dstfile) srcfile=path1+str(ns)+'.tif.rbox.txt' dstfile=path2+str(ns)+'.tif.rbox.txt' mycopyfile(srcfile,dstfile)
執行結果如下: