python实现文件重命名

要过年放假回家了,还下载了几步电影、电视剧什么的给老爸老妈看,其中下载的一些电视剧文件的文件名中前面有很长的广告信息,我想把广告信息去掉,而保留有意义的部分。例如,希望把“[电影天堂-www.dygod.com]新水浒传01.rmvb”重命名为“新水浒传01.rmvb”。由于一个个手动修改很麻烦,所以就想到用Python写几行代码来搞定它。
用Python实现的文件重命名的代码(基于python3)如下所示,实现的是广告前缀去掉。
[电影天堂-www.dygod.com]新水浒传01.rmvb —> 新水浒传01.rmvb

# -*- coding: gb2312 -*-

'''
Created on 2013-1-27

@author: Jay Ren
@module: rename_files
@note: rename files in a Windows system.
'''

import os
import re

path = "D:\\temp"

def rename_files():
    prefix = "\[电影天堂-www\.dygod\.com\]"
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path,file))==True:
            if re.match("\[电影天堂-www\.dygod\.com\].+", file):
                new_name = re.sub(prefix, "", file)
#               print(file)
#               print(new_name)
                os.rename(os.path.join(path,file),os.path.join(path,new_name))

if __namei_ == '__main__':
    rename_files()


以上代码用的目录路径为Windows格式。

另外,从这次开始,我还是决定尽量遵守Python核心程序库的代码风格(至少是缩进方式),使用4个空格来做为一个层次的缩进。

Python社区推荐的代码风格,请参考:www.python.org/dev/peps/pep-0008

master

Stay hungry, stay foolish.

3 Comments

  1. Coder们都是懒人,懒人改变世界,其实是懒人让世界更美好.哈哈
    文件重命名工具有一个,很强悍.值得推荐.
    Bulk-Rename-Utility
    没有办不到,只有想不到.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

*