用python实现文件转移,到另一个目录中

帮朋友的忙,遇到了文件上传功能,自己写了一个

希望有需要这个的人一点帮助微笑

#encoding:utf-8
import os,sys
import shutil
from shutil import Error
from shutil import copystat
from shutil import copy2

def copy_file(src_file, dst_dir): 
    #声明函数 copy_file( 要复制的文件,目标目录,复制符号连接内容到新目录,没有要忽略文件)
   
    '''复制一个文件中所以的东西到另一个目录中'''
    if os.path.isfile(src_file):
        if os.path.isdir(dst_dir):      #dst目标存在时,就pass,不存在就创建
            pass
        else:
            os.makedirs(dst_dir)
   
        errors = []                             #声明 errors列
        print src_file
        srcname = src_file   
        filename = os.path.basename(src_file)
        dstname = os.path.join(dst_dir, filename)   #将路径名(dst)添加到文名(name)之前然后赋值给 dstcname
        from shutil import Error
        try:                                #尝试
            if os.path.isfile(srcname):        #如果srcname文件是存在
                copy2(srcname, dstname)
                print srcname,dstname,'success'
            elif os.path.isdir(dstname):          #目标文件存在,删除后,再复制新的
                os.remove(dstname)
                print 'remove %s' % dstname
                copy2(srcname, dstname)
           
        except (IOError, os.error), why:                #除(IOError[与文件有关的异常],操作系统异常)外,返回原因
            errors.append((srcname, dstname, str(why))) # 向errors列里添加,(要复制的目录,目标目录,错误原因)
        # catch the Error from the recursive jiecptree so that we can  从递归复制中捕捉这个错误,以便于我们能继续复制其他文件
        # continue with other files
        except Error, err:              #除错误外,返回错误:
            errors.extend(err.args[0])  #扩展 errors 列,添加(err.args[0] 元素)
           
           
        try:                                #尝试
            copystat(srcname, dstname)              # 从srcname表示的文件复制其权限位,上次访问时间,最后修改时间 到 dst,
        except WindowsError:                # 除 Windows错误 外:
            # can't copy file access times on Windows   在Windows上无法复制文件访问时间
            pass                            # 通过(不作任何处理)
        except OSError, why:                # 除 操作系统错误 外,返回原因:
            errors.extend((src_file, dst_dir, str(why))) #扩展 errors 列,添加(要复制的文件,目标目录,错误原因)
        if errors:                          # 如果错误
            raise Error(errors)             # 提示错误
    else:
        print 'the fisrt parm should be a file name'
   
   
if __name__ == '__main__':
    if len(sys.argv) != 3:
        print 'need srcFile and dstDir'
        sys.exit(-1)
    srcFile = sys.argv[1]
    dstDir = sys.argv[2]
    copy_file(srcFile, dstDir)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值