问题说明:
用B站客户端下载的多P学习视频命名方式是"视频编号.mp4",无法直接看出视频所表达的内容,还是要依赖于客户端播放对应的视频(如下图所示)。
需求说明:
将下载的视频赋予其原本分P后的名称,并从单独的文件移到主文件中,避免繁琐文件的操作。
实现:
1. 说明
在每个视频文件中:"视频编号+.info"文件中存放着本来的名称,只需要对其进行切割就可获得,然后再进行重命名、移文件、删除原文件即可实现需求
2. 代码
import os
import shutil
import re
def isFile(fileName):
checkIsFile = re.compile(r'\.(.*)')
if len(checkIsFile.findall(fileName)) == 0:
return True
else:
return False
def checkFile(fileName, *args):
"""
检查fileName中是否有包含args中的文件
:param fileName: 被检查文件
:param args: 待检查文件
:return: existence is True , other is False
"""
files = os.listdir(fileName)
if len(args) == 0:
return True
return set(args) < set(files)
def changeBilibiliDownloadFiles(file_path, name1, config_File_Name):
if not os.path.exists(file_path):
print('输入主文件路径错误!')
return -1
# 记录更改的文件以及未更改的文件
changeCount = 0
otherFiles = []
# 获取名称 的 正则表达式
video_name_get = re.compile(r'PartName":"(?P<PartName>.*)","Format"')
os.chdir(file_path)
# 对文件夹下面的文件进行过滤
files = os.listdir(file_path)
files = list(filter(isFile, files))
if len(files) == 0:
print('主文件下无需要修改的文件夹')
return -1
# 用以对避免重复名称的存在
newFileNameDict = dict()
for file in files:
name2 = file + '_0.mp4'
# 检查是否为包含目标文件
if not checkFile(file, name1 + name2, config_File_Name):
print('file {} not Non-existent have: {} or {}'.format(file, name1 + name2, config_File_Name))
continue
nowPath = file_path + file + '\\'
os.chdir(nowPath)
with open(config_File_Name, 'r', encoding='UTF-8') as readConfig:
# 获取视频名称
config = readConfig.read()
videoName = video_name_get.findall(config)
oldFileName = name1 + name2
newFileName = file + '_' + videoName[0] + '.mp4'
# 修改名称
os.rename(oldFileName, newFileName)
if newFileName in newFileNameDict:
# 名称字典中已存在,序号加一,并重名为"___number?.mp4"
newFileNameDict[newFileName] = newFileNameDict[newFileName] + 1
print(newFileNameDict[newFileName])
oldFileName = newFileName
newFileName = file + '_' + videoName[0] + str(newFileNameDict[newFileName]) + '.mp4'
os.rename(oldFileName, newFileName)
else:
newFileNameDict[newFileName] = 1
# 将视频转移到主目录上
shutil.move(newFileName, file_path)
# 关闭文件,并更换当前文件夹,方便后面删除
readConfig.close()
os.chdir(file_path)
shutil.rmtree(file_path + file)
# 记录修改
print('change video name {} --> {}, move to {}'.format(oldFileName, newFileName, file_path))
changeCount += 1
print('A total of {} files were changed'.format(changeCount))
print('No Change {}'.format(len(otherFiles)))
if __name__ == '__main__':
print('请输入待修改视频存放主路径:')
file_path = input('>')
if file_path[-2:] != '\\':
file_path += '\\'
print('请输入待修改视频下载时的配置文件名:')
config_File_Name = input('>')
name1 = config_File_Name[:-5] + '_'
print('Change:\nfile_path: {} \nconfig_file_name: {}'.format(file_path, config_File_Name))
changeBilibiliDownloadFiles(file_path, name1, config_File_Name)