遍历一个文件夹,把里面所有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:UsersVideoEditorDesktop301_test1_一单元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:UsersAdministratorDesktop人教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)
参考资料: