I'm trying to create a small Python script based on a dictionary with a key "name" and value "age" which should accept user input, write the dictionary to a .txt file and open then output the contents of the file into Pretty Table with columns called "Name", "Age". All the names the user typed should go under the Name column with the same applying to age. The entire code is inside a while loop and only closes if the user types "quit". What I'm willing to achieve is when the user types quit the program should print all the previous names and ages inside the file including the ones typed before exiting the program into Pretty Table.
Here is my code:
from prettytable import PrettyTable
import os
sw_dir = "C:\\Users\\user\\Documents\\"
dir_change = os.chdir(sw_dir)
test_dict = {}
active = True
name_table = PrettyTable(["Name", "Age"])
filename = "name_dict.txt"
while active:
with open(filename, "a") as a_file:
user_name = input("Enter name: ")
user_age = input("Enter age: ")
user_exit = input("Type quit to exit: ")
test_dict[user_name] = user_age
if user_exit == "quit":
active = False
for name, age in test_dict.items():
a_file.write(str(name) + ":" + str(age) + "\n\n")
with open(filename, "r") as r_file:
for test_dict in r_file:
name_table.add_row([name, age])
print(name_table)
The problem is that the program only prints out the names (multiple times) that were typed before quitting, but it doesn't print the folder names inside the file i.e. the entire file.
Output sample:
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
+---------------+-----+
+---------------+-----+
| Name | Age |
+---------------+-----+
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Grace Johnson | 26 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
| Elliot McLane | 42 |
+---------------+-----+
I would really appreciate it if someone could give me a hand as I'm still kind of new to Python, and have been struggling with this issue for days.