1.傻瓜式
import os
path='D:\\baiduyundownload\\struts2'
keyword='_Struts2_'
rekeyword='_'
all_files=os.listdir(path)
for filename in all_files:
if os.path.isfile(path+'\\'+filename) and filename.find(keyword)!=-1:
os.rename(path+'\\'+filename,path+'\\'+filename.replace(keyword,rekeyword,1))
2.定义函数式
import os
path='D:\\baiduyundownload\\struts2'
keyword='_Struts2_'
rekeyword='_'
def getpath(path):
if path.strip()!='':
try:
os.chdir(path)
except os.error:
print (path+":No such dir...")
else:
path=os.getcwd()
return path
def findFiles(path,keyword):
all_files=os.listdir(path)
files=[]
for filename in all_files:
if os.path.isfile(path+'\\'+filename) and filename.find(keyword)!=-1:
files.append(filename)
return files
def replaceKeyword(fiels,keyword,rekeyword):
refiles=[]
for filename in files:
refiles.append(filename.replace(keyword,rekeyword,1))
return refiles
def renamefiles(files,refiles,path):
for i in range(len(files)):
try:
os.rename(path+'\\'+files[i],path+'\\'+refiles[i])
except os.error:
print(path+'\\'+files[i]+':wrong')
path=getPath(path)
files=findFiles(path,keyword)
refiles=replaceKeyword(files,keyword,rekeyword)
renameFiles(files,refiles,path)
以上代码来源自网络
展示代码为核心思想,可以拓展完善~用于学习,不过先各个系统都有批量修改文件名的小软件,所以以上代码没有测试 :)