尝试打开一个类似字典的txt文件,并将其内容打印到Python中的PrettyTable中



我正在尝试创建一个基于字典的小Python脚本,该脚本带有一个键"name";以及值"0";年龄;它应该接受用户输入,将字典写入.txt文件并打开,然后将文件的内容输出到Pretty Table中;名称"年龄";。用户键入的所有名称都应放在"名称"列下,并与年龄相同。整个代码在while循环中,并且只有当用户键入"while"时才关闭;退出";。我想实现的是,当用户键入退出时,程序应该将文件中以前的所有名称和年龄打印到Pretty Table中,包括退出程序前键入的名称和年龄。

这是我的代码:

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) + "nn")
with open(filename, "r") as r_file:
for test_dict in r_file:
name_table.add_row([name, age])
print(name_table) 

问题是,程序只打印出退出前键入的名称(多次(,但不打印文件中的文件夹名称,即整个文件。

输出样本:

| 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 |
+---------------+-----+

如果有人能帮我一把,我将不胜感激,因为我还是Python的新手,并且已经在这个问题上挣扎了好几天。

需要注意的几件事。

首先,字典键只能有一个值,并且键不能重复。所以,你不会得到你用一本看起来像的字典寻找的结果

{
"Grace Johnson": "26",
"Grace Johnson": "26",
#...
"Elliot McLane": "42",
"Elliot McLane": "42",
}

你需要一个更像的结构

[
{"Name": "Grace Johnson", "Age": "26"},
{"Name": "Grace Johnson", "Age": "26"},
# ....
{"Name": "Elliot McLane", "Age": "42"},
{"Name": "Elliot McLane", "Age": "42"},
]

在任何一种情况下,下一个问题都是一本字典或一份合适的字典列表确实需要编写完整的文件,如果你只想边写边附加,你可以查看";json行";数据格式。请参阅:https://jsonlines.org/

无论如何,考虑到这些限制(并忽略PrettyTable,因为它似乎与问题无关(,这里有一种方法可以继续。

import json
file_name = "name_dict.txt"
## ---------------------------
## Open our datafile (creating it is needs be)
## ---------------------------
with open(file_name, "a+") as a_file:
a_file.seek(0)  # reset the pointer back to the start of the file
test_dict = json.loads(a_file.read() or "{}")
## ---------------------------
while True:
if "quit" == input("Type quit to exit: "):
break
user_name = input("Enter name: ")
user_age = input("Enter age: ")
test_dict[user_name] = user_age
## ---------------------------
## Write the complete dictionary back out
## ---------------------------
with open(file_name, "w") as a_file:
json.dump(test_dict, a_file)
## ---------------------------
for key, value in test_dict.items():
print(f"{key} --> {value}")

最新更新