简体   繁体   English

将文件移动到文件夹或进行重命名的副本(如果目标文件夹中存在)

[英]Move file to a folder or make a renamed copy if it exists in the destination folder

I have a piece of code i wrote for school: 我有一段为学校写的代码:

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")

what this code is doing is looking for files in a source directory and then if a certain extension is found the file is moved to that directory. 该代码的作用是在源目录中查找文件,然后如果找到某个扩展名,则将该文件移至该目录。 This part works. 这部分有效。 If the file already exists in the destination folder of the same name add 1 at end of the file name, and before the extension and if they are multiples copies do "1++". 如果该文件已存在于同名目标文件夹中,则在文件名末尾,扩展名前加上1 (如果它们是倍数),请添加“ 1 ++”。 Like this: test1.c , test2.c , test3.c I tried using os.isfile(filename) but this only looks at the source directory. 就像这样: test1.ctest2.ctest3.c我尝试使用os.isfile(filename) ,但是这仅仅着眼于源目录。 and I get a true or false. 我得到了对或错。

To test if the file exists in the destination folder you should os.path.join the dest folder with the file name 要测试文件是否存在于目标文件夹中,您应该使用文件名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

If you want to have put the renaming logic in a separate function using glob and re this is one way: 如果您想使用glob将重命名逻辑放在单独的函数中并re命名,这是一种方法:

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)

I din't test the code. 我没有测试代码。 But something like this should do the job:- 但是像这样的事情应该可以做到:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果字符串等于文件文件夹,则将文件复制到目标文件夹 - Copy Files to Destination Folder if String Equals File Folder 如果目标文件夹中已存在文件,如何替换文件? - How can I replace a file if already exists in the destination folder? 将图像变量复制到目标文件夹 - Copy image variable to a destination folder 不工作:将在.csv 文件中找到的文件复制到列表中,然后如果在某个文件夹中,则复制到目标文件夹 - not working: copy files found in .csv file to list, then if in certain folder, copy to destination folder 如果已存在同名文件,则将文件移动到文件夹并重命名 - move a file to a folder and rename it if a file with the same name already exists 重命名文件夹中的文件,重命名的文件在excel表中 - Rename the files in a Folder, the file to renamed are in excel sheet 将文本文件中列出的特定文件从源文件夹复制到目标文件夹 - Copy the specific files listed in text file from source folder to Destination folder 如果数据库中存在文件夹A中的文件名移动到文件夹B,如果文件不存在,将文件名插入数据库并将文件移动到文件夹C - If filename in folder A exists in Database move to folder B, If file does not exist, insert filename into database and move file to folder C 使用 shutil.move(),我如何将文件移动到目标文件夹并同时将文件保留在源文件夹中 - Using shutil.move(), how do i move the file to destination folder and keep the file in the source folder at the same time 将指定数量的文件从源文件夹移动到目标文件夹 - Move specified number of files from source folder to destination folder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM