问题描述
打开文件夹中的所有.txt文件,
查找匹配用户提供的正则表达式的所有行,
并将结果输出在屏幕上
代码如下:
import os
import re
d = []
for filename in os.listdir(os.getcwd()):if filename.endswith('.txt'):a = os.path.join(os.getcwd(), filename)d.append(a)print(a)
print('Please input rex :')
rex = input()
for i in range(len(d)):file = open(d[i], 'r')filecontent = file.read()Regex = re.compile(rex)mo = Regex.findall(filecontent)print(mo)
输出结果:
C:\WORK\Count\mainFunction\123.txt
Please input rex :
\d
['1', '2', '3', '1', '2', '3', '1', '2', '4', '4', '1', '4']