I have a folder with contains photo of students, with the following naming format:
StudentID_Name-Number
for example: 37_GOWDA-Rohan-1204-06675
I want to keep the 37
only, some students might have a longer ID (123
, 65857
....)
How may I do this using python, I am assuming I need the os
lib.
You could use something like this to list all contents of the directory, pull the student id's, find the file type, and create a new name and save it in the same directory:
import os
# full directory path to student pictures
student_pic_path = 'full directory path to student pics'
# get all student picture filenames from path
fnames = os.listdir(student_pic_path)
# iterate over each picture
for fname in fnames:
# split by underscore and capture student id name
new_name = fname.split('_')[0]
# get the file type
file_type = fname.split('.')[-1]
# append file type to new name
new_name = '{}.{}'.format(new_name, file_type)
os.rename(os.path.join(student_pic_path, fname),
os.path.join(student_pic_path, new_name))