擅长:python、mysql、java
<p>在文件上迭代并转换为int的Pythonic方法:</p>
<pre><code>for line in open(fname):
if line.strip(): # line contains eol character(s)
n = int(line) # assuming single integer on each line
</code></pre>
<p>你要做的事情稍微复杂一点,但仍然不是直截了当的:</p>
<pre><code>h = open(fname)
for line in h:
if line.strip():
[int(next(h).strip()) for _ in range(4)] # list of integers
</code></pre>
<p>这样它一次处理5行。在Python 2.6之前使用<code>h.next()</code>,而不是<code>next(h)</code>。</p>
<p>您拥有<code>ValueError</code>的原因是<code>int</code>无法将空字符串转换为整数。在这种情况下,您需要在转换之前检查字符串的内容,或者除非出现错误:</p>
<pre><code>try:
int('')
except ValueError:
pass # or whatever
</code></pre>