python實現——根據txt檔案進行檔案複製並重命名
阿新 • • 發佈:2018-12-11
需求:根據txt檔案中所列檔名及路徑,將這些檔案複製到另外一個資料夾下並重命名,另外,重新生成一份已複製檔案的檔案路徑及檔名列表。
txt檔名:imglist.txt
原檔案所在資料夾:789
目標資料夾:000
新txt檔名:newlist.txt
實現程式碼:
# -*- coding: utf-8 -*- import time import os import shutil def re_mycopyfile(srcfile,dstfile,num): name_long=6 l=len(str(num)) zero='00000000' if not os.path.isfile(srcfile): print "%s not exist!"%(srcfile) else: #fpath,fname=os.path.split(dstfile) #分離檔名和路徑 if not os.path.exists(dstfile): os.makedirs(dstfile) #建立路徑 dstfile=dstfile+zero[:name_long-l-1]+str(num)+'.jpg' print dstfile shutil.copyfile(srcfile,dstfile) #複製檔案 print "copy %s -> %s"%( srcfile,dstfile) if __name__ == '__main__': path1="/Users/sunny/Desktop/imglist.txt" path2="/Users/sunny/Desktop/789/" path3="/Users/sunny/Desktop/000/" path4="/Users/sunny/Desktop/newlist.txt" begin=0 count=begin with open(path1,'r')as f: for line in f: line=line.split('\n') print line[0] count=count+1 dstfile=path3 re_mycopyfile(line[0],dstfile,count) count=begin name_long=6 l=len(str(count+1)) zero='00000000' with open(path1,'r')as f: for line in f: count=count+1 out_words=line.split('/') out_words[-1]=zero[:name_long-l-1]+str(count)+'.jpg' with open(path4,'a+') as fp: fp.write("/".join(out_words)+"\n")