正文

Python 3 文件重命名2012-08-02 17:36:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/tld5yj/53692.html

分享到:

一段 Python 3 编写的重命名脚本,仅用于文件,不包括文件夹,一般说来文件重命名更实用点儿,自己用自己的东西怎么都顺手,递归是好东西:

import os
import re

def BatchRenameFile(string_path, string_old_name, string_new_name): # We need three parameters, the path contains all the files you want to rename, the regular expression strings for old and new names
    re_old_name = re.compile(string_old_name) # re object compiled for match the files whose name need to be changed
    string_contents = os.listdir(string_path) # List all files and sub folders in current folder
    for string_content in string_contents: # For every object
        if os.path.isdir(string_content): # If it's a folder, enter it and execute this method in it, when finish, go back to parent folder
            os.chdir(string_content)
            BatchRenameFile(os.getcwd(), string_old_name, string_new_name)
            os.chdir('..')
        else: # If it's not a folder and can be matched by the re object for old name, perform rename
            if re_old_name.match(string_content):
                result = re.sub(string_old_name, string_new_name, string_content)
                os.rename(string_content, result)

#--------------------------------------------------------------------------------------------------#

print('\nBatch Rename Files\n') # Some parameters need to be provided by users, "RE" means you should enter a regular expression string, "NRE" means just a normal string
string_path = input('Please input the path contains all the files you want to rename (NRE):\n')
string_old_name = input('Please input the regular expression represents the old file names (RE):\n')
string_new_name = input('And input the regular expression you want the file names be changed to (RE):\n')
os.chdir(string_path)
BatchRenameFile(string_path, string_old_name, string_new_name)


如果有需要的自己改改功能吧,虽然对于各位来说基本没什么参考价值。

阅读(6920) | 评论(2)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册