当附加到csv时,我的第一行是从现有的最后一行开始,而不是从新行开始。
我一直在寻找,但我只是发现了在追加模式下打开csv或在写入csv时使用追加模式的基本用法。我无法理解这里接受的答案(to_csv append mode is not appending to next new line),因为它似乎要求在用f.write("/n")
编写("/n")之前打开现有的文件。这个答案(How to add pandas data to an existing csv file?)是最相关的,但我希望在一个函数中写入多个数据帧,所以我不想一直打开它们。我的计划是使用如下函数:
import os
def mysave(df,dfpath):
# if file does not exist write header
if not os.path.isfile(dfpath):
df.to_csv(dfpath, index = False)
else: # else it exists so append without writing the header
df.to_csv(dfpath, mode = 'a', index = False, header = False)
mysave(mydf, 'foo.csv')
我已经用foo.csv创建了一个非常简单的示例,其结构如下:
a b c d
5 1 ah doo
6 2 bah poo
7 2 dah coo
当我使用我的函数或这个简单的代码时:
import pandas as pd
df = pd.read_csv('foo.csv', index_col=False)
mydf = df
mydf.to_csv('foo.csv', mode='a', index = False, header = False)
这就是foo.csv最终的结果:
a b c d
5 1 ah doo
6 2 bah poo
7 2 dah coo5 1 ah doo
6 2 bah poo
7 2 dah coo
当我尝试添加一个回车字符作为标题时,像mydf.to_csv('foo.csv', mode='a', index = False, header = ("/n"))
一样,pandas (正确地)忽略了我错误的标题注释,并使用默认值header = True
。
a b c d
5 1 ah doo
6 2 bah poo
7 2 dah cooa b c d
6 2 bah poo
7 2 dah coo
发布于 2018-08-15 07:06:09
我也遇到过类似的问题,经过一番搜索,我没有找到任何简单优雅的解决方案。对我有效的最小修复是:
import pandas as pd
with open('foo.csv') as f:
f.write('\n')
mydf.to_csv('foo.csv', index = False, header = False, mode='a')
发布于 2016-11-11 16:45:40
如果您的数据帧变得很大,并且您希望避免连接,那么可以使用
import csv
with open('foo.csv','ab') as out:
writer=csv.writer(out)
writer.writerow(())
在函数中,或者只是作为代码中的代码片段。如果你不是在Windows上,也许你可以避免在open中添加'b‘,只用'a’(append)打开文件。
https://stackoverflow.com/questions/40542979
复制相似问题