【发布时间】:2020-05-05 01:20:22
【问题描述】:
问题:如何在运行程序时打开文件并将其转换为字典?
所以我创建了一个测试字典,将其保存为 .txt 和 .dat。下面我手动输入了字典,但我希望程序在运行时打开文件,将其转换为字典,然后继续进入函数。
(程序的总体目标是输入一个密钥(productCode)来检索产品编号,所有这些都有效),但我希望它对文件进行操作,而不是手动输入的数据。
一如既往,感谢您的指导!
file = open("test.dat", "r")
FILENAME = "test.dat"
# ------ Global Variables -------
d = {'ABCD': '0123', 'HJKL': '0987'}
user_cont = True
# ------- Functions -------
print("Product number finder.")
def get_productNum2():
global d
user_cont = True
while user_cont:
productCode = input("Enter an existing product code: ")
if productCode in d:
productNum = d[productCode]
print("Product #: " + productNum)
else:
print("Error finding product number; product code does not exist.")
user_cont = user_continue()
def user_continue():
global user_cont
prompt_user = input("Do you wish to continue? Enter y/n: ")
if prompt_user == "y":
user_cont = True
elif prompt_user == "n":
user_cont = False
return user_cont
# ------- Start Execution -------
get_productNum2()
【问题讨论】:
-
你是如何保存你的字典的,即。保存文件的格式是什么?你腌了吗? JSON?
-
@Kos 用户输入了文件名(见下文)。对于此测试,我将其设为“test.dat”。然后我将它复制到一个 .txt 文件中,并将这些内容复制并粘贴为我的 d= {} 以测试程序的其余部分。我看到了 pickle 和 json,但觉得它超出了我目前的基础。编辑:哦,评论中的格式太糟糕了......``` FILENAME = input(str("请输入文件名:")) file = open(FILENAME, "w") file.write(str(products)) file.close() print("文件已保存。")```
-
请解释“感觉这是我目前的基本情况”。您似乎不想使用提供的标准模块来解决您所询问的确切问题。
-
不要只是将 dict 的字符串表示形式写入文件,这不是您进行序列化的方式。查看
json或pickle -
@PaulCornelius 我正在编辑我的评论。它现在说“感觉它超出了我目前的基础。”看起来 JSON 和/或 pickle 是正确的选择。我还没有开始使用这些模块,只知道制作文件。
标签: python file dictionary key