的時候所以我在這個格式ValueError異常試圖添加到字典在Python
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異常的意圖的功能:值過多解壓(預期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()
http://stackoverflow.com/q/17653954/1971805不是欺騙(有點)但巧合多? – TerryA