所以我有一个这种格式的文件
CountryCode CountryName
USA United States
我要做的是以代码为键,以国家名称为值的字典。
我有一个旨在这样做的功能
def country(string):
'''reads the contents of a file into a string and closes it.'''
#open the file
countryDict = {}
fin = open(string, 'r')
for eachline in fin:
code, country = eachline.split()
countryDict[code] = country
print (countryDict)
return countryDict
但是,当我尝试运行它时,我得到 ValueError: too many values to unpack (expected 2)。
这段代码不起作用的任何原因?我有一个类似的程序,它使用这样的代码创建用户名。
供参考的用户名程序代码,这行得通,为什么上面没有:
def main():
print ("This program creates a file of usernames from a")
print ("file of names.")
# get the file names
infileName = input("What file are the names in? ")
outfileName = input("What file should the usernames go in? ")
# open the files
infile = open(infileName, 'r')
outfile = open(outfileName, 'w')
# process each line of the input file
for line in infile:
# get the first and last names from line
first, last = line.split()
# create a username
uname = (first[0]+last[:7]).lower()
# write it to the output file
print(uname, file=outfile)
# close both files
infile.close()
outfile.close()
print("Usernames have been written to", outfileName)
if __name__ == '__main__':
main()