python批量替換文件名中的共同字符實(shí)例
今天看新概念視頻的時(shí)候播放器PotPlayer的播放列表總是不能正確排序,我看到這些視頻的名字格式如下:
Lesson 1-2 單詞解讀.mp4
我認(rèn)為是數(shù)字前面的Lesson和空格干擾了播放器的排序,就考慮把這個(gè)文件夾下所有的文件名批量刪除Lesson和空格,使之變成:
1-2 單詞解讀.mp4
這里主要使用的就是os模塊下的listdir,chadir和rename三個(gè)方法
雖然最后還是排序不正確,我只能怪播放器不好了。
代碼如下
# -*- coding: UTF-8 -*-import os#獲得文件夾下文件名列表path=r'G:BaiduNetdiskDownload第1冊(cè)'path=unicode(path,'utf8')file_list=os.listdir(path)#選擇要重命名的文件夾路徑os.chdir(path)#將文件名中的Lesson和空格用空字符串替代for file in file_list: os.rename(file,file.replace('Lesson ',''))
程序在調(diào)試的時(shí)候感覺python的2.x版本中文編碼問題很擾人,最后將路徑編碼成utf-8格式解決。
補(bǔ)充知識(shí):python實(shí)現(xiàn)替換某個(gè)文件中的某個(gè)字符串(全部替換)
我就廢話不多說了,咱還是直接看代碼吧!
#!/usr/bin/python#-*-coding:utf-8-*-import click#不需要替換的文件UNMATCH = ('.DS_Store','loading','niutou_run','zhuyao')#參數(shù)設(shè)置@click.command()@click.option('-root',help=u’根目錄’)@click.option('-src',help=u’源字符’)@click.option('-dst',help=u’目標(biāo)字符’)def run(**options):root = options['root']src = options['src']dst = options['dst']for file in os.listdir(root):colorPrint('file:',file)if not isInTuple(file):jsonName = file + '.json'fileFullPath = root +'/' + file + '/' + jsonNamefp = open(fileFullPath,'r+')tempStr = fp.read()result = re.sub(src,dst,tempStr)colorPrint('seek1:',fp.tell())fp.seek(0,0)colorPrint('seek2:',fp.tell())fp.write(result)fp.close()#是否在UNMATCH中def isInTuple(name):for temp in UNMATCH:if name == temp:return Truebreakreturn False#彩色打印def colorPrint(desc,str):print(’033[1;31;40m’)print(desc,str)print(’033[0m’)if __name__ == ’__main__’:run()
以上這篇python批量替換文件名中的共同字符實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
