Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename the filename using python

I have folder where I have multiple files. Out of this files I want to rename some of them. For example: PB report December21 North.xlsb, PB report November21 North.xslb and so on. They all have a same start – PB report. I would like to change their name and leave only PB report and Month. For example PB report December.

I have tried this code:

import os

path = r'C://Users//greencolor//Desktop//Autoreport//Load_attachments//'
for filename in os.listdir(path):
    if filename.startswith("PB report"):
     os.rename(filename, filename[:-8])

-8 indicates that I want to split the name from the end on the 8th character

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I get this error:

FileNotFoundError: [WinError 2] The system cannot find the file specified

Any suggestion?

>Solution :

You need the path when renaming file with os.rename:

Replace:

os.rename(filename, filename[:-8])

With:

filename_part, extension = os.path.splitext(filename)
os.rename(path+filename, path+filename_part[:-8]+extension)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading