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方法进行正则替换掉文件名中不需要字符

相关文章

Python的Django框架中从url中捕捉文本的方法

每个被捕获的参数将被作为纯Python字符串来发送,而不管正则表达式中的格式。 举个例子,在这行URLConf中: (r'^articles/(?P<year>\...

Python随机生成身份证号码及校验功能

GitHub : https://github.com/jayknoxqu/id-number-util 身份组成方式 中华人民共和国国家标准GB 11643-1999《公民身份号码》中...

Python学习笔记(一)(基础入门之环境搭建)

Python学习笔记(一)(基础入门之环境搭建)

  Python入门       本系列为Python学习相关笔记整理所得,IT人,多学无害,多多探索,激发学习兴趣,开拓思维...

Python使用get_text()方法从大段html中提取文本的实例

如下所示: <textarea rows="" cols="" name="id"><DIV style="TEXT-INDENT: 18pt; mso-char-...

Python 多线程搜索txt文件的内容,并写入搜到的内容(Lock)方法

废话不多说,直接上代码吧! import threading import os class Find(threading.Thread): #搜索数据的线程类 def __i...