今天看新概念视频的时候播放器PotPlayer的播放列表总是不能正确排序,我看到这些视频的名字格式如下:
Lesson 1-2 单词解读.mp4
我认为是数字前面的Lesson和空格干扰了播放器的排序,就考虑把这个文件夹下所有的文件名批量删除Lesson和空格,使之变成:
1-2 单词解读.mp4
这里主要使用的就是os模块下的listdir,chadir和rename三个方法
虽然最后还是排序不正确,我只能怪播放器不好了。
代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# -*- coding: UTF-8 -*- import os #获得文件夹下文件名列表 path = r "G:\BaiduNetdiskDownload\第1册" path = unicode (path, "utf8" ) file_list = os.listdir(path) #选择要重命名的文件夹路径 os.chdir(path) #将文件名中的Lesson和空格用空字符串替代 for file in file_list: os.rename( file , file .replace( "Lesson " ,"")) |
程序在调试的时候感觉python的2.x版本中文编码问题很扰人,最后将路径编码成utf-8格式解决。
补充知识:python实现替换某个文件中的某个字符串(全部替换)
我就废话不多说了,咱还是直接看代码吧!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
#!/usr/bin/python #-*-coding:utf-8-*- import click #不需要替换的文件 UNMATCH = ( ".DS_Store" , "loading" , "niutou_run" , "zhuyao" ) #参数设置 @click .command() @click .option( "-root" , help = u '根目录' ) @click .option( "-src" , help = u '源字符' ) @click .option( "-dst" , help = u '目标字符' ) 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() |