【问题标题】:Move file to a folder or make a renamed copy if it exists in the destination folder将文件移动到文件夹或重命名副本(如果目标文件夹中存在)
【发布时间】:2015-05-11 16:30:05
【问题描述】:

我有一段我为学校写的代码:

import os

source = "/home/pi/lab"
dest = os.environ["HOME"]

for file in os.listdir(source):
   if file.endswith(".c")
      shutil.move(file,dest+"/c")
   elif file.endswith(".cpp")
      shutil.move(file,dest+"/cpp")
   elif file.endswith(".sh")
      shutil.move(file,dest+"/sh")

这段代码所做的是在源目录中查找文件,然后如果找到某个扩展名,则将文件移动到该目录。这部分有效。如果文件已经存在于同名的目标文件夹中,则在文件名末尾添加1,并且在扩展名之前并且如果它们是多个副本,则执行“1++”。 像这样:test1.c,test2.c,test3.c 我尝试使用 os.isfile(filename) 但这仅查看源目录。我得到一个真或假。

【问题讨论】:

    标签: python file-copying


    【解决方案1】:

    要测试文件是否存在于目标文件夹中,您应该 os.path.join dest 文件夹和文件名

    import os                                                                       
    import shutil                                                                      
    source = "/home/pi/lab"
    dest = os.environ["HOME"]                                                                                
    
    # Avoid using the reserved word 'file' for a variable - renamed it to 'filename' instead
    for filename in os.listdir(source):                                             
        # os.path.splitext does exactly what its name suggests - split the name and extension of the file including the '.'
        name, extension = os.path.splitext(filename)                                
        if extension == ".c":                                                       
            dest_filename = os.path.join(dest, filename)                            
            if not os.path.isfile(dest_filename):                                      
                # We copy the file as is
                shutil.copy(os.path.join(source, filename) , dest)                  
            else:                       
                # We rename the file with a number in the name incrementing the number until we find one that is not used. 
                # This should be moved to a separate function to avoid code duplication when handling the different file extensions                                        
                i = 0                                                                  
                dest_filename = os.path.join(dest, "%s%d%s" % (name, i,     extension)) 
                while os.path.isfile(dest_filename):                                   
                    i += 1                                                                                                                      
                    dest_filename = os.path.join(dest, "%s%d%s" % (name, i, extension))
                shutil.copy(os.path.join(source, filename), dest_filename)    
        elif extension == ".cpp"
            ...
            # Handle other extensions
    

    如果您想使用 globre 将重命名逻辑放在单独的函数中,这是一种方法:

    import glob
    import re
    ...
    def rename_file(source_filename, source_ext):                                   
        filename_pattern = os.path.join(dest, "%s[0-9]*%s"                          
                                        % (source_filename, source_ext)) 
        # Contains file such as 'a1.c', 'a2.c', etc...
        existing_files = glob.glob(filename_pattern)
        regex = re.compile("%s([0-9]*)%s" % (source_filename, source_ext))          
        # Retrieve the max of the index used for this file using regex
        max_index = max([int(match.group(1))                                        
                         for match in map(regex.search, existing_files)
                         if match])                                                   
        source_full_path = os.path.join(source, "%s%s"                              
                                        % (source_filename, source_ext))            
        # Rebuild the destination filename with the max index + 1 
        dest_full_path = os.path.join(dest, "%s%d%s"                                
                                      % (source_filename,                           
                                         (max_index + 1),                           
                                         source_ext))                               
        shutil.copy(source_full_path, dest_full_path)
    
     ...
     # If the file already exists i.e. replace the while loop in the else statement
     rename_file(name, extension)
    

    【讨论】:

      【解决方案2】:

      我不测试代码。但是这样的事情应该可以完成工作:-

      i = 0
      filename = "a.txt"
      while True:
          if os.isfile(filename):
              i+= 1
          break
      if i:
          fname, ext = filename.split('.')
          filename = fname + str(i) + '.' + ext
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多