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

来源:互联网 发布:果语榨汁机骗局知乎 编辑:程序博客网 时间:2024/06/11 12:42


用来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()

 

完!

原创粉丝点击