使用python pandas .to_csv附加到csv时如何强制换行 [英] How to force a new line when appending to a csv using python pandas .to_csv
问题描述
当添加到csv时,我的第一行是从现有的最后一行开始,而不是新行.
When appending to csv, my first line is starting on the existing last line rather than a new line.
我一直在搜索SO,但我只是找到在附加模式下打开csv或在写入csv时使用附加模式的基本用法.我无法理解此处接受的答案( to_csv追加模式不会追加到下一个新行),因为它似乎要求在使用f.write("/n")
写入("/n")之前打开现有文件.此答案(如何将熊猫数据添加到现有的csv文件?)最相关,但是我希望在一个函数中写入多个数据帧,所以我不想一直打开它们.我的计划是使用类似的功能:
I keep searching SO, but I am just finding the basic use of opening a csv in append mode or using append mode when writing to csv. I could not make sense of the accepted answer here (to_csv append mode is not appending to next new line) since it appears to require the existing file to be open before writing the ("/n") with f.write("/n")
. This answer (How to add pandas data to an existing csv file?) is most relevant, but I am hoping to write multiple data frames in a function, so I do not want to keep opening them. My plan is to use a function like:
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具有以下结构:
I've created a very simple example, with foo.csv with the structure:
a b c d
5 1 ah doo
6 2 bah poo
7 2 dah coo
当我使用函数或以下简单代码时:
When I use my function or this simple code:
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的最终结果:
This is what foo.csv ends up as:
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"))
熊猫(正确地)会忽略我错误的标题注释,并使用默认的header = True
.
When I attempt to add a carriage return character as the header, like mydf.to_csv('foo.csv', mode='a', index = False, header = ("/n"))
pandas (rightly) ignores my erroneous header comment and goes with the default of 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
推荐答案
我遇到了类似的问题,经过一番搜索之后,我没有找到任何简单/优雅的解决方案.对我有用的最小修复方法是:
I had a similar problem and after a god bit of searching, I didn't find any simple/elegant solution. The minimal fix that worked for me is:
import pandas as pd
with open('foo.csv') as f:
f.write('\n')
mydf.to_csv('foo.csv', index = False, header = False, mode='a')
这篇关于使用python pandas .to_csv附加到csv时如何强制换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!