擅长:python、mysql、java
<p>此处:</p>
<pre><code>while line != '':
line = test_results_file.readline()
</code></pre>
<p>当您到达文件的结尾时,<code>.readline()</code>返回一个空字符串,但是由于这发生在<code>while line != ''</code>测试之后,您仍然尝试处理这一行</p>
<p>一行一行迭代一个文件的规范(更简单)方法,也就是迭代文件,可以避免这个问题:</p>
<pre><code>for line in test_result_file:
do_something_with(line)
</code></pre>
<p>如果您想去掉结尾的换行符(您的代码就是这样),那么您只需在<code>line</code>上调用<code>.rstrip()</code></p>
<p>此外,您还需要确保无论发生什么情况,文件都已正确关闭。规范的方法是使用<code>open()</code>作为上下文管理器:</p>
<pre><code>with open("path/to/file.txt") as f:
for line in test_result_file:
do_something_with(line)
</code></pre>
<p>这将在退出<code>with</code>块时调用<code>f.close()</code>,但是它退出了(无论for循环刚刚完成还是发生了异常)</p>
<p>此外,不必进行复杂的计算来查找管道后面的零件,只需拆分字符串:</p>
<pre><code>for line in test_results_file:
total = int(line.strip().split("|")[1])
num_recs += 1
</code></pre>
<p>最后,您可以使用stdlib的<code>csv</code>模块来解析您的文件,而不是手动进行解析</p>