ValueError: invalid literal for int() with base 10: ''
我正在从文件中读取数据,这是所有数字。
我想将其更改为int,然后它显示此错误消息。
我尝试使用strip('\n')
,但我仍然遇到此错误。
filename = input('Enter a filename: ')
infile = open(filename,'r')
outfile = open('REPORT-'+filename,'w')
count_year = 0
total_ballots = 0
percentage = 0
less_year= 0
line = infile.readline()
while line !='':
line=line.strip('\n')
year = int(infile.readline())
estimated = int(infile.readline())
registered = int(infile.readline())
ballots = int(infile.readline())
if ((ballots)/(estimated))*100<60:
less_year +=1
elif ((ballots)/(estimated))*100>80:
big_year +=1
total_ballots = total_ballots + float(ballots)
outfile.write('In '+ year + ', '+str(format((float(registered)/float(estimated))*100,'.2f')) +
'% registered and ' + str(format((float(ballots)/float(estimated))*100,'.2f')) + '% voted')
percen = format((float(registered)/float(estimated))*100, '.2f')
percentage = percentage + float(percen)
count_year +=1
line=infile.readline()
average = average/count_year
print('The total number of years listed:',count_year)
print('Total ballots cast in all these years:',total_ballots)
print('Average percentage of eligible voters registered:',average,'%')
print('Number of years with less than 60% of registered voters casting ballots:', less_year)
print('Percentage of years with more than 80% of registered voters casting ballots:',(big_year/count_year)*100 )
print('An output file named '+'REPORT-'+filename+' has created.')
infile.close()
outfile.close()
这是我的输入文件
1958
1703200
1375035
978400
1962
1813500
1446593
971706
1966
1869400
1472054
987134
1970
2078000
1562916
1123000
1974
2419000
1896214
1044425
1978
2651000
1960900
1028854
1982
3119000
2105563
1404831
1986
3307000
2230354
1358160
1990
3650000
2225101
1362651
1994
4000000
2896519
1733471
1998
4257000
3119562
1939421
2002
4519000
3209648
1808720
2006
4821000
3264511
2107370
2010
5149729
3601268
2565589
答案 0 :(得分:2)
问题是你一直在检查第一行:
line = infile.readline()
while line !='':
此条件永远不会评估为False
,并且循环将无限期地继续运行,因为while
循环中的条件未更新。
比较
num = 1
while num > 0:
# do stuff
此循环将永远运行,除非您在循环中的某处修改num
(例如num -= 1
)。
在您的情况下,循环输入,直到readline()
到达文件末尾并返回空字符串。空字符串''
无法转换为整数,显然,这就是您收到错误的原因。
要解决这个问题,我会在开头使用try ... except ...
块:
while True:
try:
year = int(infile.readline())
except ValueError:
break
这将确保在没有数据可供读取时循环结束。
关于您的其他错误,以下是一些提示:
year
)big_year
?)%
:%%
答案 1 :(得分:1)
你的文件有一个空行(也许是最后一行?)。这不能转换为int。
还有许多其他事情需要纠正,我怀疑你发布的代码应该引起很多例外。