1. 程式人生 > >python實現將某程式碼檔案複製/移動到指定路徑下 (檔案、資料夾的移動、複製、刪除、重新命名)

python實現將某程式碼檔案複製/移動到指定路徑下 (檔案、資料夾的移動、複製、刪除、重新命名)

 

 

用python實現將某程式碼檔案複製/移動到指定路徑下。
場景例如:mv ./xxx/git/project1/test.sh ./xxx/tmp/tmp/1/test.sh (相對路徑./xxx/tmp/tmp/1/不一定存在)

 

# -*- coding: utf-8 -*-
#!/usr/bin/python
#test_copyfile.py

import os,shutil

def mymovefile(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.move(srcfile,dstfile)          #移動檔案
        print "move %s -> %s"%( srcfile,dstfile)

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)

srcfile='/Users/xxx/git/project1/test.sh' #待處理原始檔
dstfile='/Users/xxx/tmp/tmp/1/test.sh'  #目標檔案

mymovefile(srcfile,dstfile)


#檔案、資料夾的移動、複製、刪除、重新命名

#匯入shutil模組和os模組
import shutil,os

#複製單個檔案
shutil.Dopy("D:\\a\\1.txt","D:\\b")
#複製並重命名新檔案
shutil.Dopy("D:\\a\\2.txt","D:\\b\\121.txt")
#複製整個目錄(備份)
shutil.Dopytree("D:\\a","D:\\b\\new_a")

#刪除檔案
os.unlink("D:\\b\\1.txt")
os.unlink("D:\\b\\121.txt")
#刪除空資料夾
try:
    os.rmdir("D:\\b\\new_a")
exDept ExDeption as ex:
    print("錯誤資訊:"+str(ex))#提示:錯誤資訊,目錄不是空的
#刪除資料夾及內容
shutil.rmtree("D:\\b\\new_a")

#移動檔案
shutil.move("D:\\a\\1.txt","D:\\b")
#移動資料夾
shutil.move("D:\\a\\D","D:\\b")

#重新命名檔案
shutil.move("D:\\a\\2.txt","D:\\a\\new2.txt")
#重新命名資料夾
shutil.move("D:\\a\\d","D:\\a\\new_d")