Search code examples
pythonpython-3.xcopyfile-renameshutil

Python 3.7 - How to check if file exists and rename


I am trying to figure out how to check if a file within my source folder, exists within my destination folder, then copy the file over to the destination folder.

If the file within the source folder exists within the destination folder, rename file within source folder to "_1" or _i+1 then copy it to destination folder.

For Example (will not be a .txt, just using this as an example, files will be dynamic in nature):

I want to copy file.txt from folder a over to folder b.

file.txt already exists within within folder b a. If I attempted to copy file.txt over to folder b, I would receive a copy error.

Rename file.txt to file_1.txt a. Copy file_1.txt to folder b b. If file_1.txt exists then make it file_2.txt

What I have so far is this:

for filename in files:
    filename_only = os.path.basename(filename)
    src = path + "\\" + filename
    failed_f = pathx + "\\Failed\\" + filename

# This is where I am lost, I am not sure how to declare the i and add _i + 1 into the code.
   if path.exists(file_path):
       numb = 1
       while True:
           new_path = "{0}_{2}{1}".format(*path.splitext(file_path) + (numb,))
           if path.exists(new_path):
               numb += 1
               shutil.copy(src, new_path)
           else:
               shutil.copy(src, new_path)
   shutil.copy(src, file_path)

Thanks much in advance.


Solution

  • import os
    for filename in files:
        src = os.path.join(path, filename)
        i = 0
        while True:
            base = os.path.basename(src)
            name = base if i == 0 else "_{}".format(i).join(os.path.splitext(base))
            dst_path = os.path.join(dst, name)
            if not os.path.exists(dst_path):
                shutil.copy(src, dst_path)
                break
            i += 1