python批量替换文件名中的共同字符实例
作者:黄河大鲤鱼 时间:2022-07-11 05:22:37
今天看新概念视频的时候播放器PotPlayer的播放列表总是不能正确排序,我看到这些视频的名字格式如下:
Lesson 1-2 单词解读.mp4
我认为是数字前面的Lesson和空格干扰了播放器的排序,就考虑把这个文件夹下所有的文件名批量删除Lesson和空格,使之变成:
1-2 单词解读.mp4
这里主要使用的就是os模块下的listdir,chadir和rename三个方法
虽然最后还是排序不正确,我只能怪播放器不好了。
代码如下
# -*- 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实现替换某个文件中的某个字符串(全部替换)
我就废话不多说了,咱还是直接看代码吧!
#!/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()
来源:https://blog.csdn.net/sinat_16432941/article/details/78161145
标签:python,替换,文件名,字符
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python Django Cookie 简单用法解析
2022-09-15 15:20:03
![](https://img.aspxhome.com/file/2023/9/65569_0s.png)
Pain 全世界最小最简单的PHP模板引擎 (普通版)
2023-11-18 09:12:06
asp 通用修改和增加函数代码
2011-03-16 11:15:00
asp截取字符串的两种应用
2009-08-19 17:11:00
php文章内容分页并生成相应的htm静态页面代码
2023-07-23 23:48:20
Silverlight VS Flash,谁更强?
2008-11-07 11:04:00
利用PyQt5中QLabel组件实现亚克力磨砂效果
2023-12-13 18:33:04
![](https://img.aspxhome.com/file/2023/5/72125_0s.jpg)
JavaScript 日期下拉选择器
2008-10-31 12:13:00
Python unittest单元测试框架的使用
2021-11-26 15:56:37
Python爬虫基础讲解之scrapy框架
2023-11-16 00:07:31
![](https://img.aspxhome.com/file/2023/6/76976_0s.png)
MySQL数据库备份的基础知识大全
2009-12-20 18:14:00
常见的在Python中实现单例模式的三种方法
2022-11-08 01:42:09
python+selenium+PhantomJS抓取网页动态加载内容
2021-01-28 15:41:24
微信小程序-拍照或选择图片并上传文件
2023-09-04 20:22:45
![](https://img.aspxhome.com/file/2023/5/56275_0s.jpg)
asp之自动闭合HTML/ubb标签函数 附简单注释
2011-02-28 11:24:00
Go语言interface详解
2023-07-05 16:55:33
Python实现并行抓取整站40万条房价数据(可更换抓取城市)
2021-09-24 10:56:43
![](https://img.aspxhome.com/file/2023/7/76067_0s.png)
PHP实现绘制二叉树图形显示功能详解【包括二叉搜索树、平衡树及红黑树】
2023-07-23 02:36:20
![](https://img.aspxhome.com/file/2023/9/553891_0s.png)
Python面向对象程序设计之私有属性及私有方法示例
2023-11-21 06:29:04
详解Python读取和写入操作CSV文件的方法
2021-03-01 23:13:43
![](https://img.aspxhome.com/file/2023/6/65526_0s.jpg)