1. 程式人生 > 程式設計 >python實現複製檔案到指定目錄

python實現複製檔案到指定目錄

這幾天在做一個數據集,由於不是很熟悉Linux下的命令,所以特地用了強大的python來做。我之前有一個數據集但是我只要裡面名稱帶有composite和normals的圖片,所以找了網上的文章看到了用shutil.copyfile來實現的方法。

# -*- coding: utf-8 -*-

import os,shutil

#shutil.copyfile應用,引數必須具體到檔名
def mycopyfile(srcfile,dstfile):
 if not os.path.isfile(srcfile):
 print("%s not exit!" % (srcfile))
 else:
 fpath,fname=os.path.split(dstfile)
 if not os.path.exists(fpath):
  os.makedirs(fpath)
 shutil.copyfile(srcfile,dstfile)
 #print("copy %s" % (srcfile,dstfile))

#這個是找到圖片的實際地址
def find_filepath(dir1_name,dir2_name,i,file_name=''):
 file_path=os.path.join(dir1_name,str(i)+file_name+'.png')
 return file_path

#這個是我自己的實際應用
if __name__=='__main__':
 dir_name=['airplane_test','bottle_test','bunny_test','car_test','motorbike_test','suzanne_test','teapot_test']
 obj=['_composite','_normals']
 cnt=0
 for i in range(7):
 direction=dir_name[i]
 #print(direction)
 for j in range(400):
  print(direction,j)
  source1=find_filepath('intrinsic',direction,j,obj[0]) #源地址
  source2=find_filepath('intrinsic',obj[1]) #源地址
  dst1=find_filepath('image2norm','testA',cnt) #目標地址
  dst2=find_filepath('image2norm','testB',cnt) #目標地址
  mycopyfile(source1,dst1)
  mycopyfile(source2,dst2)
  cnt+=1

值得注意的是,shutil.copyfile(srcfile,dstfile)裡面srcfile和dstfile必須是檔名,不能是資料夾。具體應用可以參考上面的main。

如果想要複製資料夾下的全部檔案而又不清楚檔案的具體數目,可以採用以下os.listdir的方法列出該資料夾下所有檔案的名稱,

file_path='./resuls'
dirs=os.listdir(file_path)
for dir in dirs:
 print(dir)

更多關於python檔案操作專題,請檢視:

python常用檔案操作彙總

python資料夾操作彙總

python檔案操作彙總

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。