在旧的csv文件中添加新行

时间:2019-10-22 08:10:12

标签: python csv

我想在csv文件的两列中添加数百行,如下所示(带有Sublime Text):

4564,"2,82402927004573E-05"
4565,"3,43440547204476E-05"
4566,"4,04519168926086E-05"
4567,"4,65639435774783E-05"
4568,"5,26796365520546E-05"
4569,"5,87994985608482E-05"
4570,"6,49231317058272E-05"

我想添加这样的行:

4564,"2,82402927004573E-05"
4565,"3,43440547204476E-05"
4566,"4,04519168926086E-05"
4567,"4,65639435774783E-05"
4568,"5,26796365520546E-05"
4569,"5,87994985608482E-05"
4570,"6,49231317058272E-05"
4571,"0"
4572,"0"
4573,"0"
etc...

我尝试了以下代码:

from csv import reader
import numpy as np
import csv
from mpdaf.obj import Spectrum, WaveCoord

wave = range(7308, 9349, 1)
with open('transmission_curve_HST_ACS_HRC.F606W.csv', 'a') as f:
     writer = csv.writer(f)
     writer.writerow(wave)

但是正如我所见,它在最后一行中将wave的所有数据添加到最后一行,但是我想在第一列中将其添加为每行一个数据。

任何想法如何做到这一点?

谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用pandas实现目标:

df = pd.read_csv('transmission_curve_HST_ACS_HRC.F606W.csv', header=None)
wave = pd.DataFrame(list(range(7308, 9349, 1)))
wave[1] = '0'
df = df.append(wave, ignore_index=True)
df.to_csv('transmission_curve_HST_ACS_HRC.F606W.csv', header=False, index=False)