DEV Community

loading...
Cover image for How to bulk rename PDFs with Python

How to bulk rename PDFs with Python

Stokry
Front_dev | Machine Learning Enthusiast
・1 min read

Today I will show you a simple way to bulk rename your pdf files. If you have a group of PDFs that need to be copied and renamed for multiple folders this script will help you a lot.

Let's jump to the code.

import os
import shutil
from datetime import date
from os import walk
Enter fullscreen mode Exit fullscreen mode

after importing we need to define the path:

mypath = r'C:\Users\Stokry\Desktop\python\bulk\main'
Enter fullscreen mode Exit fullscreen mode

the we need to get files to rename:

_, _, filesnames = next(walk(mypath))
Enter fullscreen mode Exit fullscreen mode

files will be copied into folders name John and Anna:

list = ['John', 'Anna']
Enter fullscreen mode Exit fullscreen mode

also, we will set a current date

today = date.today().strftime("%m_%d_%y")
Enter fullscreen mode Exit fullscreen mode

then we can create the new folders:

for name in list:
    newdir = name + '_' + today
    path = os.path.join(mypath, newdir)
    os.mkdir(path)
Enter fullscreen mode Exit fullscreen mode

this will copy the files:

for file in filesnames:
        shutil.copy(mypath + '\\' + file, path)
        os.rename(path + '\\' + file, path + '\\' + name + '' + file)
Enter fullscreen mode Exit fullscreen mode

This is our final result:

enter image description here

Thank you all.

Discussion (0)