python练习程序批量修改文件名

yipeiwu_com6年前Python基础

复制代码 代码如下:

# encoding:utf-8

##
# 文件名如:
# 下吧.mp3
##
import os,re

fs=os.listdir('xb')
for f in fs:
 ######方法一:partition获取无用字符
 #1.将文件名以'['符分为3部分
 #ls=f.partition('[')
 #2.ls[0]为需要文件名,因此获取ls[1:]
 #dirtystring = ''.join(ls[1:])
 #3.开始替换
 #newname=f.replace(dirtystring, '') + '.mp3')
 #os.rename('xb/' + f, newname)

 ######方法二:正则获取无用字符
 dirtymatch = re.search(r'\[.*?\]', f)
 if dirtymatch:
  dirtystring=dirtymatch.group(0)
  newname=f.replace(dirtystring, '') + '.mp3'
  os.rename('xb/' + f, newname)

 #注意:可以直接用re.sub方法进行正则替换掉文件名中不需要字符

相关文章

pygame游戏之旅 如何制作游戏障碍

pygame游戏之旅 如何制作游戏障碍

本文为大家分享了pygame游戏之旅的第6篇,供大家参考,具体内容如下 定义一个障碍模型函数: def things(thingx, thingy, thingw, thingh,...

python获取当前日期和时间的方法

本文实例讲述了python获取当前日期和时间的方法。分享给大家供大家参考。具体如下: import datetime # Get a datetime object now = da...

python Jupyter运行时间实例过程解析

这篇文章主要介绍了python Jupyter运行时间实例过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.Python t...

Python使用pymysql从MySQL数据库中读出数据的方法

python3.x已经不支持mysqldb了,支持的是pymysql 使用pandas读取MySQL数据时,使用sqlalchemy,出现No module named ‘MySQLdb...

Python对ElasticSearch获取数据及操作

使用Python对ElasticSearch获取数据及操作,供大家参考,具体内容如下 Version Python :2.7 ElasticSearch:6.3 代码: #!/u...