I'm trying to batch rename some photos and I wanna the second part only, e.g. renaming from 1234 - Photo_Name.jpg
to Photo_Name.jpg
.
This is my code:
import os
folder = r"C:\Users\yousef\Downloads\Pictures\\"
files = os.listdir(folder)
for file_name in files:
new_filename = file_name.split(' - ')[1]
os.rename(file_name, new_filename)
But I get this Error
File "c:\Users\yousef\Downloads\code.py", line 7, in <module>
os.rename(file_name, new_filename)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '1234 - Photo_Name.jpg' -> 'Photo_Name.jpg'
It's trying to rename the file in the current directory, not the folder you listed. Use os.path.join()
to combine a directory with a filename.
import os
folder = r"C:\Users\yousef\Downloads\Pictures\\"
files = os.listdir(folder)
for file_name in files:
new_filename = file_name.split(' - ')[1]
os.rename(os.path.join(folder, file_name), os.path.join(folder, new_filename))