如何重命名以下文件:
abc_2000.jpg
abc_2001.jpg
abc_2004.jpg
abc_2007.jpg
Run Code Online (Sandbox Code Playgroud)
进入以下几个:
year_2000.jpg
year_2001.jpg
year_2004.jpg
year_2007.jpg
Run Code Online (Sandbox Code Playgroud)
相关代码是:
import os
import glob
files = glob.glob('abc*.jpg')
for file in files:
os.rename(file, '{}.txt'.format(???))
Run Code Online (Sandbox Code Playgroud)
zha*_*gyu 16
import os
import glob
files = glob.glob('year*.jpg')
for file in files:
os.rename(file, 'year_{}'.format(file.split('_')[1]))
Run Code Online (Sandbox Code Playgroud)
一行可以打破:
for file in files:
parts = file.split('_') #[abc, 2000.jpg]
new_name = 'year_{}'.format(parts[1]) #year_2000.jpg
os.rename(file, new_name)
Run Code Online (Sandbox Code Playgroud)