我想在现有文件中添加一个新列,并希望将输出写入另一个文件。我打开文件如下,并添加我需要的语句。如何通过在末尾添加新列(使用列名称/标题)将输出写入文件。分离是标签。
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 :(得分: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
答案 1 :(得分:0)
如果您事先知道新列的名称,则可以编写以下代码,如果不是这种情况,您可以在for循环内的first_line
条件下计算它。
另外,我们从values行获取最后一个值(并将其设置为每行的最后一个值),如果您需要其他行为,只需更改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')
希望它有所帮助,