简体   繁体   English

读取文件并将其转换为字典

[英]Reading a file and converting it into a dictionary

I have this text file:我有这个文本文件:

this is name_of_liquid(string)=amount(int)这是name_of_liquid(string)=amount(int)

liquid1=200

liquid2=20

liquid_X_= empty

liquid_3= 3000

now, the name does not really matter however the amount does.现在,名称并不重要,但数量却很重要。 It has to be an int.它必须是一个整数。 If it is any other type beside int the program would raise an exception如果它是除 int 之外的任何其他类型,程序将引发异常

Here is my code/ pseudocode:这是我的代码/伪代码:

#opening the file
d={}

try:
  dic = {}
  with open('accounts.txt') as f:
     for line in f:
        (key , val) = line.split()
        d[key] = int(val)
#except ValueError:
#    print('The value for', key,'is', value,' which is not a number!')

the except block is commented because that is my pseudocode and how I planed in handling the error, but when I run this code without using exception handling, I get an error of 'not enough values to unpack' Can anyone please help me?注释了 except 块,因为这是我的伪代码以及我计划如何处理错误,但是当我在不使用异常处理的情况下运行此代码时,我收到“没有足够的值来解包”的错误有人可以帮助我吗?

Try this尝试这个

f = open("acounts.txt", "r")
dict = {}

try:
    for line in f:
        line = line.split("=")
        dict[line[0]] = int(line[1])
except:
print("Invalid value for key.")

You should split the lines with = as delimiter and strip the list to get rid of extra whitespaces.您应该使用=作为分隔符拆分行并删除列表以消除多余的空格。

I personally think that the try catch block should be used while adding elements to the dictionary.我个人认为在向字典中添加元素时应该使用 try catch 块。

The following code should work for your problem.以下代码应该可以解决您的问题。

d = {}
with open('accounts.txt', 'r') as f:
    for line in f:
        (key , val) = map(str.strip,line.split("="))
        try:
            d[key] = int(val)
        except ValueError:
            print('The value for', key,'is', val,' which is not a number!')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM