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:
JavaScript
x
7
1
import os
2
3
path = r'C://Users//greencolor//Desktop//Autoreport//Load_attachments//'
4
for filename in os.listdir(path):
5
if filename.startswith("PB report"):
6
os.rename(filename, filename[:-8])
7
-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:
JavaScript
1
2
1
os.rename(filename, filename[:-8])
2
With:
JavaScript
1
3
1
filename_part, extension = os.path.splitext(filename)
2
os.rename(path+filename, path+filename_part[:-8]+extension)
3