【问题标题】:How to search a string and save the matched line in another file如何搜索字符串并将匹配的行保存在另一个文件中
【发布时间】:2022-07-28 23:20:09
【问题描述】:

我有一个看起来像这样的文本文件:

Type: Local Logon   Date:  7/28/2022 6:10:06 PM     Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/28/2022 6:10:06 PM     Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/28/2022 6:01:16 PM     Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/28/2022 6:01:16 PM     Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/28/2022 5:42:16 PM     Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/27/2022 4:13:27 PM     Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/27/2022 4:13:27 PM     Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/27/2022 11:11:27 AM    Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/27/2022 11:11:27 AM    Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/27/2022 11:10:53 AM    Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL
Type: Local Logon   Date:  7/27/2022 11:10:53 AM    Status: Success User:  USER     Workstation:  DESKTOP-I4FGAIL

我想编写一个 python 代码,在其中我可以从文本文件中找到一个特定的字符串,复制该行并将其保存到另一个文件中。假设我想搜索日期“7/28/2022”并保存所有包含该字符串的行。

import re
ans = input("What do you want to search?")
with open(r'D:\Cyber_security\Python\test.txt') as f:
    for line in f:
        match = re.search(ans, line)
        print(match)
        myfile = open(r'D:\Cyber_security\Python\ab.bat', 'w+')
        myfile.write(match)
        myfile.close()
        if match is not None:
            print("Not found")

我试过这个......但结果是匹配中的“无”

【问题讨论】:

  • 你有什么问题?这是一个非常基本的问题,所以我想您正在学习编程 - 请包括您的尝试并解释它有什么问题。带有条件的简单for 循环应该可以工作。
  • 请把它放在你的问题中(edit),而不是作为评论:它是不可读的

标签: python


【解决方案1】:
file = open("file_name", "r")
saved_lines = []
for line in file:
   if "Date: 7/28/2022" in line:
       saved_lines.append(line)

这会将包含所需日期的所有行添加到列表中

【讨论】:

  • 不应该是“for line in file.readlines()”?
  • 问题是关于“保存在另一个文件中”,所以你只需要写而不是追加。并关闭文件,更好 - 使用上下文管理器 (with open(...) as file: ...)
  • @FaridFakhry 不。这个解决方案更好(内存效率更高):file 是一个迭代器并在行上循环,而readlines() 将所有字符串放入内存并返回list
猜你喜欢
  • 1970-01-01
  • 2021-01-21
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 1970-01-01
  • 2014-02-13
  • 2021-08-30
相关资源
最近更新 更多