Python复制移动文件到其他目录

复制文件到指定文件夹

import os
import shutil
def mycopyfile(srcfile,dstpath):                       # 复制函数
    if not os.path.isfile(srcfile):
        print ("%s not exist!"%(srcfile))
    else:
        fpath,fname=os.path.split(srcfile)             # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)                       # 创建路径
        shutil.copy(srcfile, dstpath + fname)          # 复制文件
        print ("copy %s -> %s"%(srcfile, dstpath + fname))
 
 
src_dir = './'
dst_dir = './copy/'                                    # 目的路径记得加斜杠
src_file_list = glob(src_dir + '*')                    # glob获得路径下所有文件,可根据需要修改
for srcfile in src_file_list:
    mycopyfile(srcfile, dst_dir)                       # 复制文件

移动文件到指定文件夹

import os
import shutil
def mymovefile(srcfile,dstpath):                       # 移动函数
    if not os.path.isfile(srcfile):
        print ("%s not exist!"%(srcfile))
    else:
        fpath,fname=os.path.split(srcfile)             # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)                       # 创建路径
        shutil.move(srcfile, dstpath + fname)          # 移动文件
        print ("move %s -> %s"%(srcfile, dstpath + fname))
 
 
src_dir = './'
dst_dir = './move/'                                    # 目的路径记得加斜杠
src_file_list = glob(src_dir + '*')                    # glob获得路径下所有文件,可根据需要修改
for srcfile in src_file_list:
    mymovefile(srcfile, dst_dir)                       # 移动文件
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容