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中decorator使用实例

在我以前介绍 Python 2.4 特性的Blog中已经介绍过了decorator了,不过,那时是照猫画虎,现在再仔细描述一下它的使用。 关于decorator的详细介绍在 Python...

python 读取目录下csv文件并绘制曲线v111的方法

实例如下: # -*- coding: utf-8 -*- """ Spyder Editor This temporary script file is located here:...

Python接收Gmail新邮件并发送到gtalk的方法

本文实例讲述了Python接收Gmail新邮件并发送到gtalk的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python # -*- coding...

Python中遍历列表的方法总结

Python中遍历列表有以下几种方法: 一、for循环遍历 lists = ["m1", 1900, "m2", 2000] for item in lists: print(i...

Python使用tkinter库实现文本显示用户输入功能示例

Python使用tkinter库实现文本显示用户输入功能示例

本文实例讲述了Python使用tkinter库实现文本显示用户输入功能。分享给大家供大家参考,具体如下: #coding:utf-8 from Tkinter import * cl...