だから私はこの形式のファイルを持っています
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()