Home > Mobile >  Copy and rename files in the same folder
Copy and rename files in the same folder

Time:08-20

I have 3 files that I frequently need to replicate (make no changes except the name):

"IIIa_1.pdf" into 3 files: "IIIa_x.pdf", "IIIa_y.pdf", "IIIa_z.pdf"

And the same with "IIIb_1.pdf" and "IIIc_1.pdf".

I do it manually but I'm starting to learn python and I want to make it automatic.

I am 100% beginner, so I searched around and found a code similar to this:

 import os
import shutil

def navigate_and_rename(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate_and_rename(s)
        else if s.endswith("IIIa_1.pdf"):
            shutil.copy(s, os.path.join(src, "IIIa_x.pdf"))
            shutil.copy(s, os.path.join(src, "IIIa_y.pdf"))
            shutil.copy(s, os.path.join(src, "IIIa_z.pdf"))

           if s.endswith("IIIb_1.pdf"):
            shutil.copy(s, os.path.join(src, "IIIb_x.pdf"))
            shutil.copy(s, os.path.join(src, "IIIb_y.pdf"))
            shutil.copy(s, os.path.join(src, "IIIb_z.pdf"))

           if s.endswith("IIIc_1.pdf"):
            shutil.copy(s, os.path.join(src, "IIIc_x.pdf"))
            shutil.copy(s, os.path.join(src, "IIIc_y.pdf"))
            shutil.copy(s, os.path.join(src, "IIIc_z.pdf"))

dir_src = r"G:\abc\xyz\python\"
navigate_and_rename(dir_src)

When I try to run it, I get a message "expected ':'" and it highlights the if in "else if", but I am using ':', so I need help with this and maybe other mistakes in the code.

CodePudding user response:

You need to use the elif construction instead of else if

CodePudding user response:

Solved using this format:

import os
import shutil

def navigate_and_rename(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate_and_rename(s)
        elif s.endswith("file1.pdf"):
            shutil.copy(s, os.path.join(src, "newfile1.pdf"))
            shutil.copy(s, os.path.join(src, "newfile2.pdf"))
            shutil.copy(s, os.path.join(src, "newfile3.pdf"))

        elif s.endswith("file2.pdf"):
            shutil.copy(s, os.path.join(src, "newfile4.pdf"))
            shutil.copy(s, os.path.join(src, "newfile5.pdf"))
            shutil.copy(s, os.path.join(src, "Newfile6.pdf"))

        elif s.endswith("file3.pdf"):
            shutil.copy(s, os.path.join(src, "newfile7.pdf"))
            shutil.copy(s, os.path.join(src, "newfile8.pdf"))
            shutil.copy(s, os.path.join(src, "newfile9.pdf"))

dir_src = r"PATH TO FOLDER"
navigate_and_rename(dir_src)
  • Related