使用 Python 将列添加到现有的 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40229469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a Column to an existing CSV file with Python
提问by Schviteza
I'm trying to add a new column header and values to an existing csv file with python. Every thing I've looked up appends the header to the last row of the last column. This is what I want my results to be essentially.
我正在尝试使用 python 向现有的 csv 文件添加新的列标题和值。我查找的所有内容都将标题附加到最后一列的最后一行。这就是我希望我的结果是基本。
Header Header2 Header3 NewHeader
Value Value2 Value3 NewValue
Header Header2 Header3 NewHeader
Value Value2 Value3 NewValue
What I'm currently getting is this:
我目前得到的是:
Header Header2 Header3
Value Value2 Value3**NewHeader
NewValue`
This is my code:
这是我的代码:
import csv
with open('filename.csv', 'a') as csvfile:
fieldnames = ['pageviewid']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'pageviewid': 'Baked'})
writer.writerow({'pageviewid': 'Lovely'})
writer.writerow({'pageviewid': 'Wonderful'})
回答by Carlos Alvarenga
If using pandas is an option:
如果使用熊猫是一种选择:
import pandas as pd
df = pd.read_csv('filename.csv')
new_column = pd.DataFrame({'new_header': ['new_value_1', 'new_value_2', 'new_value_3']})
df = df.merge(new_column, left_index = True, right_index = True)
df.to_csv('filename.csv', index = False)
回答by Chris Kenyon
Easiest way would be to rewrite to an output file
最简单的方法是重写到输出文件
import csv
reader = csv.reader(open('filename.csv', 'rb'))
writer = csv.writer(open('output.csv', 'w'))
headers = reader.next()
headers.append("Brand New Awesome Header")
writer.write(headers)
for row in reader:
row.append(new data for my new header)
writer.writerow(row)