且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python 中文正则表达匹配

更新时间:2022-09-08 14:47:30

需求:由于某个n年前的工具的错误,在复制一批文件的时候产生了大量的"复件xxxxxxx""复件(2)XXXXX"等类似文件,由于目录结构深,文件多,预计在5000万个,但是有多少这种错误的文件不清楚,因此写个脚本遍历删除。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#encoding=utf-8
#author: skybug
#date: 2014-05-11
#function: 遍历指目录,删除中文开头的文件名的图片
import os,re
cnt = 0
pattern = re.compile(ur"[\u4e00-\u9fa5].*")#定义正则匹配表达式
#pattern = re.compile(ur"[\u590D][u4EF6].*")
def walkdir_del(srcdir):#遍历目录
    global cnt
    for parent,dirs,files in os.walk(srcdir):
        for file in files:
            infile = os.path.join(parent,file)
            file = file.decode('gb2312').encode('utf8')#将文件名字符串转码
            file = unicode(file,'utf8')#同上
            match = pattern.match(file)#匹配
            if match:#如果匹配
                print infile
                os.remove(infile)#删除
                cnt +=1
                print "del %s ok!"%infile
                print "del %d files"%cnt
       
       
srcdir=os.getcwd()
walkdir_del(srcdir)

      本文转自天山三害 51CTO博客,原文链接:http://blog.51cto.com/skybug/1409589,如需转载请自行联系原作者