Ask Your Question
0

Can you assist me in renaming all the PDF files in a directory using two specific criteria in Python?

asked 2022-06-04 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-10-28 12:00:00 +0000

david gravatar image

Sure. Here's a Python code snippet that renames all the PDF files in a directory based on two criteria:

  1. Adding a prefix to the file name
  2. Removing a specific string from the file name
import os

# Define the directory containing the PDF files
directory = "/path/to/directory"

# Define the prefix to be added to the file name
prefix = "new_"

# Define the string to be removed from the file name
remove_string = "old_"

# Loop through all the PDF files in the directory
for filename in os.listdir(directory):
    if filename.endswith(".pdf"):
        # Rename the file by adding a prefix and removing the specified string
        new_filename = prefix + filename.replace(remove_string, "")
        os.rename(directory+"/"+filename, directory+"/"+new_filename)

In this code, you need to replace "/path/to/directory" with the path to the directory containing the PDF files you want to rename. You also need to replace "new" with the prefix you want to add to the file names and "old" with the string you want to remove from the file names.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-04 11:00:00 +0000

Seen: 9 times

Last updated: Oct 28 '21