Home > Enterprise >  Moving files with the same names in one folder without overwritten?
Moving files with the same names in one folder without overwritten?

Time:03-01

I made a script for organize files, and it working well. my issue happen when it overwritten files with the same name. so i made a variable [i] inside while loop to added if the moving file exists.

from genericpath import isdir
import os
import shutil

# Set File Path ------------------------------
print(os.getcwd())
path = os.chdir(os.path.dirname(os.path.abspath(__file__)))

# Set Dict for files Extensions. -------------
IMAGES = (".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png")

VIDEOS = (
    ".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", 
        ".vob", ".mng", ".qt", ".mpg", ".mpeg", ".3gp"
    )

ARCHIVES = (
    ".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", 
        ".7z", ".dmg", ".rar", ".xar", ".zip"
    )

AUDIO = (
    ".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p",       
        ".mp3", ".msv", "ogg", "oga", ".raw", ".vox", ".wav", 
           ".wma"
    )

DOCUMENTS = (
    ".pdf", ".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf",
         ".ods", ".odt", ".pwi", ".xsn", ".xps", ".dotx",     
             ".docm", ".dox", ".rvg", ".rtf", ".rtfd", ".wpd",
                ".xls", ".xlsx", ".ppt", "pptx", ".csv", ".txt", 
                   ".in", ".out"
    )

 PROGRAMS = (".exe", ".msi")

# Set list of Files in current dir. ----------
dir_list = os.listdir(path)

# Moving Files. ------------------------------
print('\n>>>> Start Organizing Files. <<<<\n')
for file in dir_list:
    i = 1
    if file == 'Folder-Organizer.py':
        pass

# Move [IMGs]. --------------------------------
    if file.endswith(IMAGES):
        while os.path.isfile(f'{path}\IMGs\{file}'):
            i  = 1
            duplicated = os.path.splitext(file)
            file = f'{duplicated[0]}{i}{duplicated[1]}'
        
        shutil.copy(file, 'IMGs')
        os.remove(file)

But it raising This Error each time the loop running.

in copyfile with open(src, 'rb') as fsrc:    
FileNotFoundError: [Errno 2] No such file or directory:

CodePudding user response:

For every one have the same issue, I found the solution. The shutil.move raise error (file not found) bcz the while loop change file name inside python environment but not in the directory. So you need to use os.rename module to change the file to the new name first then the shutil.move do the rest.

CodePudding user response:

Use os.path.exists instead of os.path.isfile .

  • Related