利用晚上在实验室的时间,和同学一起做点半公益性质的小项目,因为我的时间一直有限,所以很惭愧,就做了一点微小的工作。
今天遇到的问题是:
在一个文件夹下,按年份季度分文件夹存有所有产品的图片,但是他们格式并不统一,有些是:XXXX-1305-10_01.jpg ,有些就是简单的1305_01.jpg或者1305_02jpg。
其中尾巴上的01,02是正反面,需要保留。所以想精简下,统一成1305_01.jpg格式。
不多说,看了一个正则表达式和os文件夹的操作,实际编代码只写了10几分钟。
关于OS操作的:
点击打开链接
看的正则表达式主要是:
链接1
链接2
链接3
还有其他的一些,这些里面讲正则表达式的讲的很好,包括match和search但是有一点我这里要在提一下:
如果你需要提取的是上下文相关的字符串,那么必须像我下面代码那样使用括号
如果你在匹配规则里使用了括号,那么返回的group(0)默认就会是整个字符串。相对应的,group(1)就是第一个括号匹配内容,group(2)是第二个括号匹配内容。
当然match和search只会返回第一个匹配的子串,如果要匹配多个可以使用findall方法。
如果是上下文无关的代码,那么可以不用括号:
# encoding: UTF-8
import re
# 将正则表达式编译成Pattern对象
pattern = re.compile(r'world')
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
# 这个例子中使用match()无法成功匹配
match = pattern.search('hello world!')
if match:
# 使用Match获得分组信息
print match.group()
### 输出 ###
# world
下面上我自己的代码:
# encoding: UTF-8
__author__ = 'Arthur'
import re
import os
def changeFileName(oldname,path):
text=oldname
print(text)
m = re.search(r'^\S+\-([0-9]+)\-\S+\_(\d+)\.jpg$', text)
if m:
number1=m.group(1)
number2=m.group(2)
newname=number1+'_'+number2+".jpg"
print("newname:"+newname)
newDirname=os.path.join(path,newname)
print("newdirname:"+newDirname)
oldDirname=os.path.join(path,oldname)
os.rename(oldDirname,newDirname)
else:
print ('not search')
def dealWithDir(path):
if os.path.exists(path):
print(path)
files=os.listdir(path)
for file in files:
subpath=os.path.join(path,file)
print("subpath:"+subpath)
if os.path.isfile(subpath):
filename=os.path.basename(subpath)
print("filename:"+filename)
changeFileName(filename,path)
else :
dealWithDir(subpath)
else:
print("no such path,check please")
if __name__=='__main__':
test="C:\\test"
dealWithDir(test)
console端输出:C:\Python34\python.exe C:/AppServ/www/cotest/python_script/changeimgname.py
Process finished with exit code 0
改名成功!当然这里只是用了test文件夹下只有2个文件(其中1个文件在c:/test/test2文件夹中)。