Python 添加新列 header
Python adding new column with header
我想在现有文件中添加一个新列,并将输出写入另一个文件。我按如下方式打开文件并添加我需要的语句。如何通过在末尾添加新列(使用列 name/Header)将输出写入文件。分隔符是制表符。
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
提前致谢。
假设您事先知道新列的名称,您可以编写以下代码,如果不是这种情况,您可以在 for 循环内的 first_line
条件下计算它。
此外,我们从值行中获取最后一个值(并将其设置为每行的最后一个值),如果您需要其他行为,只需更改 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')
希望对您有所帮助,
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
我想在现有文件中添加一个新列,并将输出写入另一个文件。我按如下方式打开文件并添加我需要的语句。如何通过在末尾添加新列(使用列 name/Header)将输出写入文件。分隔符是制表符。
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
提前致谢。
假设您事先知道新列的名称,您可以编写以下代码,如果不是这种情况,您可以在 for 循环内的 first_line
条件下计算它。
此外,我们从值行中获取最后一个值(并将其设置为每行的最后一个值),如果您需要其他行为,只需更改 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')
希望对您有所帮助,
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