zoukankan      html  css  js  c++  java
  • python26实例[文件copy和自动rename]


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

    完!

  • 相关阅读:
    centos 下PATH变量配置错误补救办法 Alex
    基于php模块方式安装LAMP和常见LAMP应用 Alex
    php配置 Alex
    php测试小代码 Alex
    PHP简介 Alex
    2.7.JavaScriptnull与undefined
    2.9.JavaScript内置对象
    2.8.JavaScript不同数据类型转换
    2.2.javascript变量作用域
    2.6.Javascript数值型
  • 原文地址:https://www.cnblogs.com/itech/p/1991737.html
Copyright © 2011-2022 走看看