python实现将某代码文件复制/移动到指定路径下 (文件、文件夹的移动、复制、删除、重命名)

版权声明:文章为网上公开资源结合个人情况修改整理。如有侵权,请联系删除。 https://blog.csdn.net/qq_41895190/article/details/83745078

用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")


 

猜你喜欢

转载自blog.csdn.net/qq_41895190/article/details/83745078