Search code examples
pythonstringtextreadfile

How to read a value of file separate by tabs in Python?


I have a text file with this format

ConfigFile 1.1
;
;     Version: 4.0.32.1
;     Date="2021/04/08" Time="11:54:46" UTC="8"
;
Name
    John Legend
Type
    Student
Number
    s1054520

I would like to get the value of Name or Type or Number How do I get it? I tried with this method, but it does not solve my problem.

import re
f = open("Data.txt", "r")
file = f.read()
Name = re.findall("Name", file)
print(Name)

My expectation output is John Legend Anyone can help me please. I really appreciated. Thank you


Solution

  • Assuming those label lines are in the sequence found in the file you can simply scan for them:

    labelList = ["Name","Type","Number"]
    captures = dict()
    with open("Data.txt","rt") as f:
        for label in labelList:
            while not f.readline().startswith(label):
                pass
            captures[label] = f.readline().strip()
    for label in labelList:
        print(f"{label} : {captures[label]}")