python的正则替换,re.sub
import re
a = 'sadf.4.555.asdf.123sadf.sadf'
b = re.sub(r"\.([0-9a-zA-Z]+)\.[0-9a-zA-Z]+$", "-你好啊时间-\g<1>", a)
2, 批量修改文件
#_*_ encoding: utf-8 _*_ @author: ty heris
#项目名称: pycharm_file 会自动替换为当前项目名称
#创建时间: 2018/5/8 会自动替换为当前日期
# '''
# 'ORDER BY对查询结果排序.avi'
# >>> re.search('(\d-\d+)',i2)+re.sub('-(\d-\d+)','',i2)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: unsupported operand type(s) for +: 're.Match' and 'str'
# >>> re.search('(\d-\d+)',i2).group(1)+re.sub('-(\d-\d+)','',i2)
# '8-34ORDER BY对查询结果排序.avi'
# >>> re.search('(\d-\d+)',i2).group(1)+re.sub('-(\d-\d+)','',i2)
# '8-34ORDER BY对查询结果排序.avi'
# >>>
# '''
import os, re
path = "E:/go_learn_video/麦子学院招牌课程[明星python编程视频VIP教程]/06-之mysql基础/" # 目标路径
# path = "Y:/pythons3/day01/" # 目标路径
"""os.listdir(path) 操作效果为 返回指定路径(path)文件夹中所有文件名"""
# filename_list = # 扫描目标路径的文件,将文件名存入列表
for i in os.listdir(path):
try:
print(i)
# i1 = re.search("(day.*?)\.",i).group(1)
# print('++',f'<span class="page-num">(P\d+)</span><span class="part">{i}</span>')
# a = f'<span class="page-num">(P\d+)</span><span class="part">.*?{i1}</span>'
# reg = re.compile(a)
# print('2222', i1,a)
# a2 = re.search(a,fhtml).group(1)
# a2 = re.search('<span class="page-num">(P\d+)</span><span class="part">{i}</span>', i).group(1)
# print('--',a2,type(a2) ) # ORDER BY对查询结果排序-8-34.avi
# new_name = re.sub("\d+",a2 ,i)
# a = 'sadf.4.555.asdf.123sadf.sadf'
# new_name = re.sub(r"-(\d-\d+)", "\g<1>", i)
new_name = re.sub(r"(.+)-(\d-\d+)", "\g<2>_\g<1>", i)
print(new_name)
os.rename(path + i, path + new_name)
print(new_name,"ok")
# os.rename(path + '/' + i, path + '/' + new_name)
except Exception as e :
print(new_name,e)
# with open('C:\\Users\\Administrator.USER-20190427VG\\Desktop\\c.html',encoding='utf-8') as f1:
# fhtml = f1.read()
# print('内容:',fhtml)
# re.search('<span class="page-num">(P\d+)</span><span class="part">(.*)</span>', i).group(2)
# print(i)
# used_name = path + filename_list[a]
# new_name = "_".join(re.findall(".*?-0(\d+).*_(.*)", test_str))
# print(used_name,)
# new_name = path + "new_" + filename_list[a]
# os.rename(used_name,new_name)
# print("文件%s重命名成功,新的文件名为%s" %(used_name,new_name))
# a += 1
# for j in filename_list:
# print('这个是j',j)
# try :
# print(os.path.join(path,j))
# for i in os.listdir(os.path.join(path,j)):
# try:
# print('++',i)
# new_name = re.sub("\spytho.*?-",'-',i)
# # print(path + j +'/'+ i,'福建省大反馈', path +j +'/'+ new_name)
# # print('---------',os.path.join(os.path.join(path,j),i))
# os.rename(path +j +'/'+ i, path +j +'/'+ new_name)
# except Exception :
# pass
# except Exception:
# pass
# <li class=""><a href="/video/BV1Ly4y1C7Ni?p=30" class="router-link-active" title="05-GO语言开发-day4-数组">
# <div class="link-content">
# <i class="van-icon-videodetails_play" style="display: none;"></i>
# <span class="page-num">P30</span>
# <span class="part">05-GO语言开发-day4-数组</span>
# </div>
# <div class="duration">28:59</div>
# </a></li>
写入自己的博客中才能记得长久