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
I get this error:
FileNotFoundError: [WinError 2] The system cannot find the file specified
Any suggestion?
Advertisement
Answer
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)