python批量文件重命名

import os
import re

rootdir= r'D:\rizhi\gp-2012-11'
pat = re.compile(r'google.*?(\d{8}).*?\.txt')

for n in os.listdir(rootdir):
    match = pat.match(n)
    if match:
        oldname = os.path.join(rootdir, n)
        newname = os.path.join(rootdir, ('gp' + match.group(1) + '.txt'))
        os.rename(oldname, newname)
        print newname
    else:
        print 'no'

做了python文件批量重命名的工具,使用正则对文件名进行匹配,如果匹配则修改文件名。

在这里发现了2个问题:

1、使用os.rename的时候需要用完整路径,这是就用到了os.path.join(root, filename),如果只用文件名是无法重命名的。

2、使用正则的时候,用match可匹配到括号中的字符,但需要使用match.group(1)才能使用,如果只是match.group()则会显示全部。

原文地址:https://www.cnblogs.com/alexkh/p/2943933.html