pandas导出为csv文件时,存在空行的问题

88 阅读1分钟

pandas导出为csv文件时,存在空行的问题

问题

在下述代码中,在导出csv文件中会出现大量空行。

import pandas as pd
frame = pd.DataFrame([[1, 2, 3, 4, 5], 
              [11, 22, 33, 44, 55], 
              [111, 222, 333, 444, 555]], 
              columns=['col1','col2','col3', 'col4', 'col5'])

with open('test.csv', mode='w') as writer:
    frame.to_csv(writer, index=False)

其导出文件如下图所示为:

pandas测试数据导出

解决方法

首先给出解决方法

## 解决方法1(官方推荐)
with open('test.csv', newline='', mode='w') as writer:
    frame.to_csv(writer, index=False)
    
## 解决方法2
with open('test.csv', mode='w') as writer:
    frame.to_csv(writer, index=False, lineterminator='\n')

导出文件结果如下:

解决后导出文件示意

path_or_buf: String, path object (implementing os.PathLike[str]), or file-like object implementing a write() function. If None, the result is returned as a string. If a non-binary file object is passed, it should be opened with newline=’’, disabling universal newlines. If a binary file object is passed, mode might need to contain a ‘b’.

根据上述关于to_csv()API中path_or_buf参数的解释中,如果该参数传入的为文件对象,则需要在打开时指定newline''