<p>该表一遍又一遍地重复,因为您读取了脚本顶部的文件,然后对文件中的每一行重新打开该文件。你知道吗</p>
<p>下面是一种使用<code>namedtuple</code>的方法:</p>
<pre><code>from collections import namedtuple
# define a named tuple for storing each line (record)
fields = ['Estimate_Number', 'Date', 'Final_Total', 'Customer_Number', 'Status', 'Amount_Paid']
record = namedtuple('record', fields)
# first print the header
for field in fields:
print('%-17s' % field.replace('_', ' '), end='')
print('Outstanding')
totalOutstanding = 0
# open the file using a context manager (the with keyword)
with open("pJoptionc.txt", "r") as data:
for line in data:
# strip the newline character, split on the comma and create a record
row = record(*line.strip().split(','))
# we can access each field by name now to make the code more readable
outstanding = int(row.Final_Total) - int(row.Amount_Paid)
# print the output
if outstanding:
for field in fields:
print('%-17s' % getattr(row, field), end='')
print(outstanding)
totalOutstanding += outstanding
print('Total Outstanding is... %s' % totalOutstanding)
</code></pre>
<p>参考文献:</p>
<ul>
<li><a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="nofollow">namedtuple</a></li>
<li><a href="https://docs.python.org/2/library/stdtypes.html#string-formatting" rel="nofollow">string formatting</a></li>
<li><a href="https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">argument unpacking</a></li>
</ul>