遍歷一個文件夾,把里面所有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)

