<h2>可能的解决方案</h2>
<p>有许多可能的解决方案,这一个说明了几个典型的结构</p>
<pre><code>fname = "as.txt"
with open(fname) as f:
# skip first line (containing header)
header = f.next() #this has just read one line (header)
print "header", header # just to show, we have read the header line, not really necessary
# this creates a list of records with each record being: [srno, name, enrolment, cgpa, year]
records = [line.split() for line in f]
# initialize resulting lists
y_11 = []
y_others = []
# loop over records
# we use value unpacking, each element of record is assigned to one variable
for srno, name, enrolment, cgpa, year in records:
if enrolment.startswith("11"):
y_11.append([srno, name, enrolment, float(cgpa), int(year)])
else:
y_others.append([srno, name, enrolment, float(cgpa), int(year)])
# note, as we have left the `with` block, the `f.close()` was done automatically
assert f.closed # this assert would raise an exception if the `f.closed` would not be True
# print the results
print "y_11", y_11
print "y_other", y_others
</code></pre>
<h2>叫它吧</h2>
<pre><code>$ python file2lst.py
header Sr.No. Name Enrollment Number CGPA Year
y_11 [['1.', 'XYZ', '1101111', 7.1, 2014], ['2.', 'ZYX', '1101113', 8.2, 2014]]
y_other [['3.', 'Abc', '1010101', 9.1, 2014]]
</code></pre>
<h2>很少评论</h2>
<h2><code>f.next()</code>-阅读下一行文字</h2>
<p>有了一个文件描述符,循环就可以遍历它们。所以你不用打电话</p>
<pre><code>lines = f.readlines()
</code></pre>
<p>但你也可以做到:</p>
<pre><code>lines = list(f)
</code></pre>
<p>在所有情况下,都会返回行列表。你知道吗</p>
<p>在for循环中迭代时,会使用<code>next()</code>方法隐藏对iterable的调用:</p>
<pre><code>lines = []
for line in f:
lines.append(line)
</code></pre>
<p>再一次,我们已经填充了行列表。你知道吗</p>
<p>我们可以使用iterable上的<code>next()</code>调用来实现同样的功能,在我们的例子中是openfiledescriptor。你知道吗</p>
<pre><code>with open(fname) as f:
lines = []
line = f.next()
lines.append(line)
line = f.next()
lines.append(line)
line = f.next()
lines.append(line)
line = f.next()
lines.append(line)
</code></pre>
<p>我们非常聪明,可以立即停止,否则一旦文件中的行用完,就会引发异常<code>StopIteration</code>。<code>for</code>循环自动捕获此异常并停止迭代。你知道吗</p>
<p>到现在为止,我们应该明白,通过调用<code>header = f.next()</code>,我们读出了第一行。下次在某个迭代中使用<code>f</code>时,它不会返回并跟随下一行,不再返回头。你知道吗</p>
<h2>将值解包为变量</h2>
<p>我们假设<code>line.split()</code>返回5个元素。你知道吗</p>
<p>我们可以在一个步骤中把所有5个元素分配到不同的变量中。你知道吗</p>
<pre><code>record = ["a11", "b22", "c33", "d44", "e55"]
a, b, c, d, e, = record
print a
print b
# etc.
</code></pre>
<p>在我们的解决方案中,我们在<code>for</code>循环中使用它。你知道吗</p>
<h2>上下文管理器会自动调用所创建变量的<code>close()</code></h2>
<p>处理文件的典型习惯用法如下:</p>
<pre><code>fname = "something.txt"
with open(fname) as f:
# process the file
# do not call `f.close()` as it gets closed at the moment inner `with` block is left.
</code></pre>
<p>这种<code>with</code>构造使用所谓的“上下文管理器”,它能够通过输入块(在<code>with</code>行上)并在块的末尾执行某些操作来装箱一些值,在我们的示例中,它调用<code>close()</code></p>