您好,登錄后才能下訂單哦!
今天看新概念視頻的時(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版本中文編碼問(wèn)題很擾人,最后將路徑編碼成utf-8格式解決。
補(bǔ)充知識(shí):python實(shí)現(xiàn)替換某個(gè)文件中的某個(gè)字符串(全部替換)
我就廢話不多說(shuō)了,咱還是直接看代碼吧!
#!/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 + "/" + jsonName fp = 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 True break return 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è)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。