<p>您可以尝试以下代码:</p>
<pre><code>FILE_1 = "File1.in"
FILE_2 = "File2.in"
def getTableData(file_name):
"""Retreive the Table Data from 'file_name' and return it as a list()"""
file_1 = open(file_name,'r')
data = [cols.split() for cols in file_1.read().split('\n')]
data[0].insert(0,' ')
return data
def getColumn(file_name):
"""Retrieve the new Column data from file 'file_name' and return it as a list"""
file_2 = open("File2.in", 'r')
col = file_2.read().split('\n')
return col
def appendColumn(table, col_name, col):
"""Append the new Column to the table"""
table[0].append(col_name)
for x in xrange(len(col)):
table[x+1].append(col[x])
return table
def total(table):
"""Calculate the Total in the table"""
col =[]
for i in xrange(len(table)-1):
tot = 0.0
for j in xrange(len(table[i+1])-1):
tot += float(table[i+1][j+1])
col.append(str(tot))
return col
def writeBack(file_name, table):
"""Writing the table back to 'file_name'"""
fout = open(file_name,"w")
for row in table:
line = '\t\t'.join(row)
fout.write(line + "\n")
table = appendColumn(getTableData(FILE_1), "VIETNAMESE", getColumn(FILE_2))
col = total(table)
table = appendColumn(table, "TOTAL", col)
writeBack(FILE_1, table)
</code></pre>
<p><strong>限制:</strong></p>
<ul>
<li>将在最终输出文件中打印的列将不会正确缩进。你得玩缩进。目前,每列由两个<strong><em>'\t'</em></strong>分隔。在</li>
<li>只有当要添加的新列与现有表的行数相同时,代码才有效。在</li>
<li>正如<code>Saelyth</code>已经提到的,“w”选项将删除前一个文件并创建一个新文件。所以在尝试之前一定要备份数据。在</li>
</ul>
<p>我还假设新列名不包含在第二个文件中,并且它是从另一个源接收的。在</p>
<p>您要回写的最后一个数据表是一个二维矩阵,因此您可以通过简单地执行<code>table[i][j] = "New Data"</code>来编辑(i,j)处的任何条目。在</p>