-3

I am a newbie coder. i need to achieve the above mentioned goal as i m working with around 600 downloaded pdfs with random names and want to change them to their respective titles. I hv been trying to solve this issue since the past few days but ive gone nowhere. I did find a decent 4 yr old code which did exactly what i want. But it seems to hv some issues and doesnt work on Python 3.10.

Here is the code i found: https://github.com/jdmonaco/pdf-title-rename

E_net4
  • 27,810
  • 13
  • 101
  • 139

1 Answers1

0

There are many different ways to answer this question, but in my opinion, the easiest one is using Python's module os.

To rename many files, the first thing you NEED to do is to put ALL the PDFs in one folder. Once you're done that, you can use the code below:

def batchRenmePDF(folder, newName):
    import os

    suffix = 0

    for each_pdf in os.listdir(folder):
        suffix += 1

        path = os.path.join(folder,each_pdf)

        os.rename(path,f"{newName}_{suffix}.png")

Here is a more in-depth version of the code above:

def batchRenmePDF(folder, newName):
    '''
    A function to quickly rename PDFs

    args:
        folder (str, path): The path for the folder with all the PDFs
        newName (str): The name for the new PDFs (Do not include filetypes)
    '''
    # Import required modules
    import os

    # Make sure the user's folder exists
    if os.path.exists(folder):
        pass
    else:
        print("Folder does not exist")
        exit()

    # If the user added the filetype in the newName, replace it with nothing
    if str(newName).endswith(".pdf") or str(newName).endswith(".PDF"):
        newName = str(newName).replace(".pdf","")
        newName = str(newName).replace(".PDF","")
    else:
        pass

    # Create the variable for the suffix for all the PDFs
    suffix = 0

    # Loop through all PDFs in the folder the user gave
    for each_pdf in os.listdir(folder):
        # Add 1 to the suffix so each time the PDF will have a different number
        suffix += 1

        # Create the path for the PDF using the folder path and the PDF name
        path = os.path.join(folder,each_pdf)

        # Actually renaming the PDFs
        os.rename(path,f"{newName}_{suffix}.png")
E_net4
  • 27,810
  • 13
  • 101
  • 139
Daniel
  • 83
  • 8
  • If you're curious: I imagine most of the downvotes are because the question is heavy on unnecessary verbiage, but low on specifics (for instance, what actual error even happens when they try the code—what are "some issues"?). – CrazyChucky Dec 05 '21 at 17:50
  • there might be a typo in the last line: it says png but it should say pdf, right? – Rho Apr 27 '23 at 20:39