Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print a specific line/row from a text file?

I have a text file as following:

1, Max Mustermann, Male, 1000.0
2, Nora Mustermann, Female, 790.0
3, Tomas Mustermann, Male, 400.0

i want to read the last value from the fourth column if i type the persons number and the number 1 to show the value. Unfortunately, I can’t get any further from here. How can i do this?

data_next = []
for data in open("my_data.txt"):
    liste = data.split(",")
    number = int(liste[0])
    name = liste[1]
    sex = liste[2]
    value = liste[3]
    data_next.append(number)
    print(f" [{number}] {name} {sex} {value}")


which_person = int(input("WHICH PERSON?: "))

if which_person in data_next:
    print("Do you want to know the value? Press 1 for YES or 2 for NO")
    next_input = int(input("YOUR INPUT: "))
    if next_input == 1:
        print(value)
    elif next_input == 2:
        print("THX")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to save the values as well in the structure, a dict is very well suited for that : number as key, values as value

data_next = {}
with open("my_data.txt") as fic:
    for data in fic:
        liste = data.split(",")
        number = int(liste[0])
        data_next[number] = liste[1:]
        print(f" [{number}] {liste[1:]}")

Then use the dict, to access the values

if which_person in data_next:
    print("Do you want to know the value? Press 1 for YES or 2 for NO")
    next_input = int(input("YOUR INPUT: "))
    if next_input == 1:
        print(data_next[which_person][2])
    elif next_input == 2:
        print("THX")

With regex you can handle nicely the comma+space delimiter

data_next = {}
with open("my_data.txt") as fic:
    for data in fic:
        nb, *others = re.fullmatch(r"(\d+),\s*([^,]+),\s*(\w+),\s*(\d+.?\d*)", data).groups()
        data_next[nb] = others
        print(f" [{nb}] {' '.join(others)}")
which_person = input("WHICH PERSON?: ")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading