Python批量重命名

某无聊的下午的一个小需求

1 import os
2 dirPath = r''    #路径
3 format = r''    #后缀
4 name = 0
5 for file in os.listdir(dirPath):
6     oldPath = '%s\%s'%(dirPath, file)
7     newPath = '%s\%s.%s'%(dirPath, name, format)
8     name += 1
9     os.rename(oldPath, newPath)
......

 

然后今晚(20160729)想要根据文件内容重命名来着.....

结果智障了半个小时,没关闭文件就想rename...........

 1 import os
 2 import re
 3 
 4 rootpath = r'' #路径
 5 
 6 paten = r'(?<=Title:\n).*' #按照需求写正则
 7 os.chdir(rootpath) #脚本和文件们不在同一个文件夹是需将当前路径改一下
 8 
 9 for i in os.listdir(rootpath):
10     oldname = os.path.normpath(os.path.join(rootpath, i))
11     file = open(i, 'r')
12     try:
13         newname = re.findall(paten, file.read())[0] + '.txt'
14         newname = os.path.normpath(os.path.join(rootpath, newname))
15         file.close() #先关闭再rename
16         os.rename(oldname, newname)
17     except IndexError as e: #有一个文件是跟其他不同的....在try的下一行产生IndexError
18         file.close() #记得关闭文件......
19         print(i)
View Code

 

转载于:https://www.cnblogs.com/book-book/p/5650402.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值