最新消息:重新回归WordPress,我要比较认真的开始更新我的博客了。

python批量改文件名

杂七杂八 hanlei 1331浏览

以前下载了很多电影,文件名上都有很多名称之外的信息。安装了emby后很多电影文件名无法正常识别,所以写了个python脚本,把文件名中没用的东西去掉,只丢下电影名称。

和批量编码的代码整合了一下,放到了一起,引入了命令行控制,不用每次都改代码了

#!/usr/bin/env python
#-*-coding:utf-8-*-

import os
import re
import os
import argparse
import subprocess as sp
#==================================================================
def make_argparse():
    ''' change this function for custom command line parameter.'''

    parser = argparse.ArgumentParser()

    # positional argument : parse by sequance , must be exist, 
    # must in right type , must in right sequance
    parser.add_argument("fun", help="要执行的程序。")          #default type is string
    parser.add_argument("path",  help="要处理的路径。") #custorm int type

    # optional argument : parse by key and value, no care 
    # to sequance , such as "-x=xxxx" or "-x xxxx"
    parser.add_argument("-o", "--output",  help="--------")
    parser.add_argument("-old", "--oldname",  help="原文件名格式")
    parser.add_argument("-new", "--newname",  help="新文件名格式")
    parser.add_argument("-v", "--verbosity", help="--------", action="store_true")
    #This means that, if the option is specified, assign the value True to args.verbosity.
    # Not specifying it implies False.

    args = parser.parse_args()
    return args
#==================================================================

def rename(args):
    if(not args.oldname or not args.newname):
        print("需要输入原文件名(-old)和新文件名(-new)格式!\n字符串前置$输入转义字符")
        exit()
    path=os.path.abspath(args.path)
    old=args.oldname
    new=args.newname
    files=os.listdir(path)
    for item in files:
        if item.count('.')>=1:
            #print item
            oldname=path + '/' + item
            reobj=re.search(old,item)
            if(reobj):
                num=1
                if new.count('.')==0:
                    newname=path + '/' + new + '.' + item.split('.')[-1]
                else:
                    newname=path + '/' + new
                for part in reobj.groups():
                    #print part
                    newname=newname.replace('('+str(num)+')',str(part))
                    num=num + 1
                if(not os.path.isfile(newname)):
                    os.rename(oldname,newname)
                print(oldname + '======>'+ newname+'\n')
            else:
                print oldname + "匹配失败!"

#==================================================================

def recode(args):
    path=os.path.abspath(args.path) 
    f=os.listdir(path)
    for fi in f:
        if fi.count('.')>=1:
            oldname=path + '/' + fi
            newnameParts=fi.split('.')
            name_part1=fi[0:fi.rfind('.')]
            name_part2=fi[fi.rfind('.'):]
            newname=path + '/new_' + name_part1 + '.mp4'
            newname=newname.replace(' ','\ ')
            oldname=oldname.replace(' ','\ ')
            p = sp.Popen('ffmpeg -i ' + oldname, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
            (o, e) = p.communicate()
            print(fi)
            fileinfo=(e if(len("".join(o.split()))==0) else 0)
            reobj=re.search(ur'Video:\s(\w+)[\s|,]', fileinfo)
            if(reobj):
                print(reobj.group(1))
                #continue
                #if(reobj.group(1)!='h264' and not os.path.isfile(path+ 'new_' +fi)):
                if(name_part2!='.mp4' and not os.path.isfile(newname)):
                    if(reobj.group(1)=='h264'):
                        sp.call('ffmpeg -i ' + oldname + ' -acodec copy -vcodec copy ' + newname, shell=True)
                    else:
                        sp.call('ffmpeg -i ' + oldname + ' -vcodec h264 -maxrate 2000k ' + newname, shell=True)
                if(os.path.isfile(newname)):
                    os.remove(path + '/' + fi)
                    os.rename(newname,name_part1 + '.mp4')

#main code
args = make_argparse(); 
if args.fun:
    exec(args.fun + "(args)")

代码有点莫名其妙,有时间改改

转载请注明:HANLEI'BLOG » python批量改文件名