如何停止在csv文件末尾写入空白行-Pandas

如何停止在csv文件末尾写入空白行-Pandas

问题描述:

将数据保存到csv data.to_csv('csv_data', sep=',', encoding='utf-8', header= False, index = False)时,它将在csv文件的末尾创建一个空行.

When saving the data to csv, data.to_csv('csv_data', sep=',', encoding='utf-8', header= False, index = False), it creates a blank line at the end of csv file.

如何避免这种情况?

line_terminator有关,对于新行,其默认值为n.

It's got to do with the line_terminator and it's default value is n, for new line.

有没有一种方法指定line_terminator以避免在末尾创建空白行,还是我需要读取csv文件,删除空白行并保存?

Is there a way to specify the line_terminator to avoid creating a blank line at the end, or do i need to read the csv file, remove the blank line and save it?

不熟悉熊猫.非常感谢您的帮助!

Not familiar with pandas. Your help will be appreciated, thanks in advance!

一种方法是保存除最后一个条目以外的数据,默认为line_terminator(\n),并在最后一行附加line_terminator="". /p>

One way would be to save data except the last entry,with default line_terminator(\n) and append the last line with line_terminator="" .

data1 = data.iloc[0:len(data)-1]
data2 = data.iloc[[len(data)-1]]
data1.to_csv('csv_data', sep=',', encoding='utf-8', header= False, index = False)
data2.to_csv('csv_data', sep=',', encoding='utf-8', header= False, index = False,mode='a',line_terminator="")