<p>因为它不是一个数值。因此,如果python不能将其转换为整数,它就会抛出<code>ValueError</code>。你可以用下面的代码来检查它</p>
<pre><code>def calculate_average():
test_results_file = open('studentNamesfile.txt', 'r')
total = 0
num_recs = 0
for line in test_results_file.readlines():
try:
total += int(line[line.find('|') + 1:])
num_recs += 1
except ValueError:
print("Invalid Data: ", line[line.find('|') + 1:])
test_results_file.close()
print("total:", total)
print("num_recs:", num_recs)
print("Average:", float(total)/num_recs)
</code></pre>
<h2>读线与读线</h2>
<pre><code>from io import StringIO
s = 'hello\n hi\n how are you\n'
f = StringIO(unicode(s))
l = f.readlines()
print(l)
# OUTPUT: [u'hello\n', u' hi\n', u' how are you\n']
f = StringIO(unicode(s))
l1 = f.readline()
# u'hello\n'
l2 = f.readline()
# u' hi\n'
l3 = f.readline()
# u' how are you\n'
l4 = f.readline()
# u''
l5 = f.readline()
# u''
</code></pre>
<h2>读线</h2>
<p>如果我们使用<code>readlines</code>,那么它将返回一个基于<code>\n</code>字符的列表</p>
<h2>读线</h2>
<p>从上面的代码中我们可以看到,<code>stringIO</code>中只有3行,但是当我们访问<code>readline</code>时,它总是给我们一个空字符串。因此,在您的代码中,您将它转换为整数,因为您将得到<code>ValueError</code>异常</p>