move a file to a folder and rename it if a file with the same name already exists

Viewed 49

I want to move one or more files into an "archive" subfolder. However, I'm having trouble handling the case where a file with the same name already exists in this "archive" file.

For the moment I add a string ("new_") before the name of the file (filename.xlsx -> new_filename.xlsx) but I don't like this way of doing things… I would rather rename it like this: (filename.xlsx- > filename_1.xlsx)

Moreover, this way does not take into account, if yet another file with the same name have to be moved.

File 1 : src\filename.xlsx ---> src\archive\filename.xlsx (ok)
File 2 : src\filename.xlsx ---> src\archive\new_filename.xlsx (ok)
File 3 : src\filename.xlsx -x-> (problem) 

The goal is to have something like this :

File 1 : src\filename.xlsx ---> src\archive\filename.xlsx 
File 2 : src\filename.xlsx ---> src\archive\filename_1.xlsx 
File 3 : src\filename.xlsx -x-> src\archive\filename_2.xlsx 

Here what I did so far :

import os
import shutil
from pathlib import Path

src = r'C:\testonsdestrucs'  

for file in os.listdir(src): 
    full_path = os.path.join(src, file)
    
    if not os.path.isdir(full_path): 
        archive = os.path.join(src, 'Archive') 
        Path(archive).mkdir(parents=True, exist_ok=True)

        files_archive = []
        for file_archive in os.listdir(archive):
            files_archive.append(file_archive)

        if file in files_archive:
            os.rename(full_path,  os.path.join(archive, 'new_' + file) )
        else: 
            shutil.move(full_path, archive )
1 Answers
import os
import shutil                      
from pathlib import Path     

src = r'C:\testonsdestrucs'
for file in os.listdir(src):
    full_path = os.path.join(src, file)             
    if not os.path.isdir(full_path):
        archive = os.path.join(src, "Archive")
        Path(archive).mkdir(parents=True, exist_ok=True)

        files_archive = os.listdir(archive)

        if file in files_archive:
            def rename(old, count):
                new = str(count) + "_" + file
                if new in files_archive:
                    count += 1
                    rename(old, count)
                else:
                    os.rename(full_path, os.path.join(archive, new))

            rename(full_path, 1)
        else:
            shutil.move(full_path, archive)

I have tested this code. It can work right. But it add the number in the front. If you want to add the number before point. You can change the rename rules.

Related