Home > Backend Development > Python Tutorial > Python实现批量修改文件名实例

Python实现批量修改文件名实例

WBOY
Release: 2016-06-06 11:13:04
Original
1756 people have browsed it

本文实例讲述了Python实现批量修改文件名的方法。分享给大家供大家参考。具体如下:

下载了评书《贺龙传奇》,文件名中却都含有xxx有声下载,用脚本将其去掉。脚本涉及os.rename重命名方法,str.partition方法使用, 及正则match,search方法区别

# encoding:utf-8
##
# 文件名如:
# 贺龙传奇\d+[有声下吧www.ysx8.com].mp3
##
import os,re
fs=os.listdir('单田芳_贺龙传奇')
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('单田芳_贺龙传奇/' + f, newname)
  ######方法二:正则获取无用字符
  dirtymatch = re.search(r'\[.*?\]', f)
  if dirtymatch:
    dirtystring=dirtymatch.group(0)
    newname=f.replace(dirtystring, '') + '.mp3'
    os.rename('单田芳_贺龙传奇/' + f, newname)
  #注意:可以直接用re.sub方法进行正则替换掉文件名中不需要字符

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

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