简体   繁体   English

使用 Python 将列添加到现有的 CSV 文件

[英]Add a Column to an existing CSV file with Python

I'm trying to add a new column header and values to an existing csv file with python.我正在尝试使用 python 向现有的 csv 文件添加新的列标题和值。 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.这就是我希望我的结果本质上是什么。

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'})

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)

Easiest way would be to rewrite to an output file最简单的方法是重写到输出文件

import csv
reader = csv.reader(open('filename.csv', 'r'))
writer = csv.writer(open('output.csv', 'w'))
headers = reader.next()
headers.append("Brand New Awesome Header")
writer.writerow(headers)
for row in reader:
    row.append(new data for my new header)
    writer.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM