编写一个程序,打开文件夹中所有的.txt 文件,查找匹配用户提供的正则表达式的所有行。结果应该打印到屏幕上。

代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 编写一个程序,打开文件夹中所有的.txt文件,查找匹配用户提供的正则表达式的所有行。结果应该打印到屏幕上

import re
import os
import sys

cwd = os.getcwd()
txtDirList = []

# 查找匹配的文件,并存入列表
regex1 = re.compile(r'\.txt$')
for x in os.listdir(cwd):
    if regex1.search(x):
        txtDirList.append(x)
print(txtDirList)

# 根据传入的参数来匹配需要行
print(sys.argv[1])
regex2 = re.compile(sys.argv[1])
txtLineList = []
for x in txtDirList:
    with open(x, 'r', encoding='UTF-8') as txtFile:
        txtLineList = txtFile.readlines()
        for y in txtLineList:
            if regex2.search(y):
                print(y + '\n')

相关文章:

  • 2022-12-23
  • 2021-05-14
猜你喜欢
  • 2022-12-23
  • 2021-10-18
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2021-08-11
  • 2022-12-23
相关资源
相似解决方案