Rename multiple files in Python

user2536218 picture user2536218 · Jul 19, 2013 · Viewed 18.9k times · Source

How can I rename the following files:

abc_2000.jpg
abc_2001.jpg
abc_2004.jpg
abc_2007.jpg

into the following ones:

year_2000.jpg
year_2001.jpg
year_2004.jpg
year_2007.jpg

The related code is:

import os
import glob
files = glob.glob('abc*.jpg')
for file in files:
    os.rename(file, '{}.txt'.format(???))

Answer

zhangyangyu picture zhangyangyu · Jul 19, 2013
import os
import glob
files = glob.glob('year*.jpg')
for file in files:
    os.rename(file, 'year_{}'.format(file.split('_')[1]))

The one line can be broken to:

for file in files:
    parts = file.split('_') #[abc, 2000.jpg]
    new_name = 'year_{}'.format(parts[1]) #year_2000.jpg
    os.rename(file, new_name)