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

WBOY
Release: 2016-06-06 11:28:40
Original
1465 people have browsed it

代码如下:


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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!