Rename multiple files in Python
Because I have done something similar today:
#!/usr/bin/env python
import os
import sys
import re
if __name__ == "__main__":
_, indir = sys.argv
infiles = [f for f in os.listdir(indir) if os.path.isfile(os.path.join(indir, f))]
for infile in infiles:
outfile = re.sub(r'abc', r'year' , infile)
os.rename(os.path.join(indir, infile), os.path.join(indir, outfile))
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)