2015-10-17 61 views
1

我想在现有文件中添加一个新列,并且希望将输出写入另一个文件。我打开文件如下,并添加我所需的语句。如何通过在最后添加新列(使用列名称/标题)将输出写入文件。分离是标签。输入的Python添加了带有标题的新列

with open(newfile, 'w') as outfile: 
    with open(oldfile, 'r', encoding='utf-8') as infile: 
     statements: 

样品:

Col1 Col2 Col3 Col4 

Val1 Val1 Val1 Val1 
Val2 Val2 Val2 Val2 
Val3 Val3 Val3 Val3 
Val4 Val4 Val4 Val4 

输出的样品:

Col1 Col2 Col3 Col4 Col5(Newly added) 

Val1 Val1 Val1 Val1 Val1 
Val2 Val2 Val2 Val2 Val2 
Val3 Val3 Val3 Val3 Val3 
Val4 Val4 Val4 Val4 Val4 

预先感谢。

+0

现在的问题是不明确的。您显示的输出样本是针对现有文件的,对吗? – blackmamba

回答

1
import csv 

with open('data','r') as f_in: 
    with open('data_out', 'w') as f_out: 
     writer = csv.writer(f_out, delimiter=' ', lineterminator='\n') 
     reader = csv.reader(f_in, delimiter=' ') 

     result = [] 
     # read headers 
     row = next(reader) 
     # add new header to list of headers 
     row.append('Col5') 
     result.append(row) 

     for row in reader: 
      # add new column values 
      row.append(row[0]) 
      result.append(row) 

     writer.writerows(result) 

data_out 

Col1 Col2 Col3 Col4 Col5 
Val1 Val1 Val1 Val1 Val1 
Val2 Val2 Val2 Val2 Val2 
Val3 Val3 Val3 Val3 Val3 
Val4 Val4 Val4 Val4 Val4 
+0

谢谢Letzer。 – user3668772

0

假设您事先知道新列的名称,您可以编写以下代码,如果情况并非如此,您可以在for循环中的first_line条件下计算它。如果您需要其他行为,只需在for循环中更改else部分即可。如果您需要其他行为,请在for循环中更改else部分。

new_column_name = 'Col5' 
with open(newfile, 'w') as outfile: 
    with open(oldfile, 'r', encoding='utf-8') as infile: 
     for line in infile: 
      if first_line: 
       outfile.write('{} {}\n'.format(line, new_column_name)) 
       first_line = False 
      else: 
       values = line.split() 
       if values: 
        values.append(values[-1]) 
       outfile.write(' '.join(values) + '\n') 

希望它能帮助,

+0

谢谢Avenet。 – user3668772