您的位置:首页 > 编程语言 > Python开发

批量修改文件名和后缀名的python设计

2015-12-13 17:27 471 查看
闲着无事,用python写了下关于批量修改文件名的小脚本,相信很多人都有这样的情况。

脚本分为5种情况,模式及具体操作由原文件配置,可以通过修改文件中的变量实现自己的需求。

将文件拷贝到目的文件夹下运行即可,采用python 2.7运行。

#Version 1.0
#copyright sundd, sunjelly@126.com
#This script is used to change file name automatically once
#operation 0 : add some prefix, 1 : delete part of the file name begins
#2 : change file extension 3 : add some suffix 4 : delete part of the file name end

import os

path=os.getcwd()
init_old=os.listdir(path)
init_old.remove('tmp.py')

operation=4 #your operation
lendel=4 #number of string to delete
pres='pre_'
extension='.py'
sufix='suff'
init_new=[]

if operation==0:
raw_input("Add %s to file name in fornt" % pres)
for a in range(len(init_old)):
init_new.append(pres+init_old[a])
print init_new[a]
os.rename(init_old[a], init_new[a])
elif operation==1:
raw_input("Delete %d char of file name in fornt" % lendel)
for a in range(len(init_old)):
init_new.append(init_old[a][lendel:])
print init_new[a]
os.rename(init_old[a], init_new[a])
elif operation==2:
raw_input("Change file extension to %s" % extension)
for a in range(len(init_old)):
b=init_old[a].find('.')
init_new.append(init_old[a][:b]+extension)
print init_new[a]
os.rename(init_old[a], init_new[a])
elif operation==3:
raw_input("Add %s to file name in end" % sufix)
for a in range(len(init_old)):
b=init_old[a].find('.')
init_new.append(init_old[a][:b]+sufix+init_old[a][b:])
print init_new[a]
os.rename(init_old[a], init_new[a])
elif operation==4:
raw_input("Delete %d char of file name in end" % lendel)
for a in range(len(init_old)):
b=init_old[a].find('.')
init_new.append(init_old[a][:(b-lendel)]+init_old[a][b:])
print init_new[a]
os.rename(init_old[a], init_new[a])

print init_new
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息