前言
今天利用哔哩哔哩下载器下载了一堆资源,结果发现文件名全部都是乱序,没有排好序就感觉看的很蒙,突然想起python可以批量重命名于是准备利用python写一个脚本. 大概思路就是先爬取哔哩哔哩视频的标题,爬取下来后利用range生成顺序编号,通过字符串拼接起来,然后截取文件夹的名字,拿着截取的名字去查找对应的新名字和旧名字,利用python的os模块进行批量重命名
导入相关库
1 2 3 4
| import requests import json import os import fnmatch
|
获取哔哩哔哩视频下的标题
https://api.bilibili.com/x/web-interface/view/detail?bvid=av号&aid=
av号的aid可以通过f12获取,url中的aid就是图片里的pid
还有一个接口不过需要自己处理一下json数据,此代码用的上面那个接口,接口地址:
获取哔哩哔哩视频的每集的标题
1 2 3 4 5 6 7 8 9 10 11 12
| def getjson(): page_text = requests.get( 'https://api.bilibili.com/x/web-interface/view/detail?bvid=BV15741177Eh&aid=89760569') data = page_text.json() shuzi = list(range(1, 233)) data = data['data']['View']['pages'] newname = [] for shuzi, item in zip(shuzi, data): part = item['part'] mingzi = str(shuzi)+part[3:len(part)]+".mp4" newname.append(mingzi) return newname
|
截取需要查找的字符串
1 2 3 4 5 6 7
| def findName(fileList): findname = [] for fn in fileList: fname = fn[7:len(fn)-12] findname.append(fname) return findname
|
查找需要更改的需要更改的文件名字以及新名字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| def comparison(fileList, path): oa = [] newa = [] findname = findName(fileList) newname = getjson()
for fn, oldname in zip(findname, fileList):
for na in newname: if fn in oldname and fn in na and oldname.endswith('.mp4'): oa.append(oldname) newa.append(na) rename(oa, newa, path)
|
进行批量重命名
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| def rename(oldname, newname, path): path = path oldname = oldname newname = newname
for oldn, newna in zip(oldname, newname): try: oldname = path + os.sep + oldn newname = path + os.sep + newna os.rename(oldname, newname) print(oldname, '=======>', newname) except Exception as e: pass
|
定义主函数
1 2 3 4
| if __name__ == "__main__": path = 'D:\Learning world\personal project\personal project\Python\\test' fileList = os.listdir(path) comparison(fileList, path)
|
注意
请复制出一份后在测试代码 未整理前:
整理后: