python学习笔记(1)--遍历txt文件,正则匹配替换文字

遍历一个文件夹,把里面所有txt文件里的[]里的朗读时间删除,也就是替换为空。

复制代码
 1 import os
 2 import re
 3 import shutil
 4 #os文件操作,re正则,shutil复制粘贴
 5 path1 = r"" #脚本
 6 path2 = r"" #mp3
 7 
 8 #for root1, dirs1, files1 in os.walk(path1):    #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
 9 # for root2, dirs2, files2 in os.walk(path2):
10 #     for i in range(0, len(files2)):
11 #         num, other = files2[i].split('_', 1)
12 #         num_root = os.path.join(root2, files2[i]) 
13 #         #print (num)
14 #         #C:\Users\VideoEditor\Desktop\301_test\1_一单元\1_《为人民服务》\1_预习\1_音画课文
15 #         num2 = r'\\\d_.*?单元\\%s_.*?\\1_预习\\1_音画课文$' %num#这个地方好像是有贪婪匹配,加了“单元”后可用
16 #         for root1, dirs1, files1 in os.walk(path1):
17 #             if re.findall(num2, root1):
18 #                 #shutil.copy(num_root, root1)
19 #                 shutil.copy(num_root, root1+'\\' + '录音.mp3')
20 # print("导入成功!")
21 path = r"C:\Users\Administrator\Desktop\人教6下TXT"
22 for dirpath, dirnames, filenames in os.walk(path):
23     for i in range(len(filenames)):
24         filename = dirpath + "\\" + filenames[i]
25         # print(filename)
26         lines = open(filename,'r').readlines()
27         for i in range(len(lines)):
28             # re.sub才能够匹配正则,replace只能替换字符串
29             lines[i] = re.sub(r'\[.*\]','',lines[i])
30             print(lines[i])
31         open(filename,'w').writelines(lines)

转载于:https://www.cnblogs.com/medik/p/10989754.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值