Home > Mobile >  Read different data for different use from txt file in python
Read different data for different use from txt file in python

Time:05-30

I have a text file as mentioned below and my requirement is to read two types of data(command, host) based on particular key or word then use it for different purpose. Is is possible read and extract such both command and host data separately. I can achieve it by creating two different text file and read it separately. Any leads would be appreciable.

Sample text file data:

{command}

command1
command2
command3


{HOST}

1.2.3.4
d.d.d.d
w.w.w.w

CodePudding user response:

If I understand you correctly you can use re for the task:

import re

with open("your_file.txt", "r") as f_in:
    for header, group in re.findall(
        r"(\{.*?\})\s*(.*?)\s*(?=\{|\Z)", f_in.read(), flags=re.S
    ):
        print("HEADER =", header)
        print("-" * 80)
        for i, line in enumerate(group.splitlines(), 1):
            print(i, line)
        print()

Prints:

HEADER = {command}
--------------------------------------------------------------------------------
1 command1
2 command2
3 command3

HEADER = {HOST}
--------------------------------------------------------------------------------
1 1.2.3.4
2 d.d.d.d
3 w.w.w.w
  • Related