【发布时间】:2014-05-31 06:43:44
【问题描述】:
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
【问题讨论】:
-
您必须尝试转换字符串或浮点数或其他内容:向我们展示您的输入到底是什么以及您的代码是什么样的。
-
1958 1703200 1375035 978400
-
您最好将其发布在问题正文中并正确格式化,否则无法阅读。
-
line.line.strip('\n')将提升AttributeError。这应该是line = line.strip('\n')(因为int()忽略了前导和尾随空格,所以没有必要。还请显示您正在使用的输入文件。 -
您从未读入过
line的新值。如果第一次去除换行符后它是非空的,它永远不会是空的。