A homework assignment I have been working on.
I'm currently trying to read in a txt file:
Then put the names together and add the numbers. The problem is the way my code is now I "need more than 1 value to unpack" (error) and I am not sure how to do more than 2 values currently.
fname = input("Enter the name of the file you want to open: ")
fo = open(fname, "r")
d = {}
for line in fo:
(key, val) = line.strip().split(":")
d[key] = int(value)
fo.close()
You can simply write more than two values before the =
on assignment. You have five values per line, so you can write
fname, lname, val1, val2, val3 = line.strip().split(":")
But your error "need more than 1 value to unpack" signals another problem: you only get one value out of your split() and try to put it into two variables. You need to change the ":"
in the call to .split()
to the character separating the columns in your file. If it's a whitespace the following will work:
fname, lname, val1, val2, val3 = line.strip().split(" ")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.