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")
>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?: ")