Home > OS >  How to retrieve a value in a file with tab format using Python?
How to retrieve a value in a file with tab format using Python?

Time:12-13

I have a file with this format:

FileConfig
;
;     Version: 4.0.0
;     Date="2021/11/19"
;
Name
    James
Number
    1091125
Identifier
    STDNT
Byte
        7687aBap
ID
    22SSWA
Program
    *Internal
    External

I want to get the value of the string like Name , Number etc. I tried this way, but I only able to get all the string. Is there any way to get the specific value by initialize the 'Name' or Number.

file1 = open("myfile.log", "r")
print(file1.readlines())

My expectation I can get the value with this way:

file1.readlines(Name)

I really appreciate for the help. I am new with Python. Thank you so much

CodePudding user response:

I tried to save the informations that concerns you into a dictionnary and this logic is based on the file you shared :

count = 0
key = 0
dic = dict()
key_counter = 1
keys = ["Name","Number"]
with open("file.log") as fp:
    Lines = fp.readlines()
    for line in Lines:
        count  = 1
        if "FileConfig" in line.strip() or ";" in line.strip():
            pass
        elif key_counter == 1 and line[0] != " ":
            key_counter = 2
            key= line.strip()
            if key in keys:
                dic[line.strip()] =0
        elif key_counter == 1 and line[0] == " ":
            key_counter = 1
            if key in keys:
                val = dic.get(key)
                if isinstance(val, list):
                    val.append(line.strip())
                    dic[key] =val
                else:
                    dic[key] = [val,line.strip()]
        elif key_counter == 2:
            if key in keys:
                dic[key] = line.strip()
            key_counter = 1
dic

output:

  {'Name': 'James', 'Number': '1091125'}
  • Related