python26实例[文件copy和自动rename]

本文介绍了一款Python脚本工具,该工具可以智能地复制文件或文件夹,并在目标位置已有同名文件或文件夹时自动进行重命名,避免覆盖原有文件。此工具适用于需要频繁复制文件并保留所有版本的场景。


用来copy文件和目录,当文件或文件夹已经存在时,自动增加.r1,.r2......来重命名新copy的文件。

 

代码:

import os
import sys
import shutil


def copyWithRename(source, dest, rename = True):

  
if os.path.exists(dest) and rename == True:
    dir, name 
= os.path.split(dest)
    newdest 
= dest
    
if os.path.isfile(dest):
      namewithoutext, ext 
= os.path.splitext(name)
      i 
= 1
      
while(1):
        newdest 
= os.path.join(dir, namewithoutext + '.r' + str(i) + ext)
        
if os.path.exists(newdest):
          i
+=1
          
continue
        
elsebreak
    
else:
      i 
= 1
      
while(1):
        newdest 
= os.path.join(dir, name + '.r' + str(i))
        
if os.path.exists(newdest):
          i
+=1
          
continue
        
elsebreak
    dest 
= newdest
    
  
print 'Copied : ' + source + '  >>>  ' + dest

  
if os.path.isdir(source):
    shutil.copytree(source,dest)
  
else:
    shutil.copyfile(source,dest)
    

def usage():
  thescript 
= sys.argv[0]
  usage 
= '\n\
  Function:\n\
    Copy file or folder and rename it with .rx suffix\n\
    when the same file or folder is already existed.\n\
  Usage:\n\
    python %s source dest\n\
  Eexamples:\n\
    python %s "c:\\test\\test.txt" "c:\\test2\\test.txt"\n\
    python %s "c:\\test\\test1" "c:\\test\\test2"\n\
  Notes:\n\
      source and dest must be same type, such as both of them are file or dir.\n\
  
' % (thescript,thescript,thescript)
  
print usage

if __name__ == '__main__':
  
if len(sys.argv) == 3
    copyWithRename(sys.argv[
1], sys.argv[2])
  
else:
    usage()

 

完!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值