简体   繁体   中英

Pandas: Write CSV file with Windows line ending

Example:

import pandas as pd
df = pd.DataFrame({'A':[1,2], 'B':[3,4]})
df.to_csv('test.csv', line_terminator='\r\n')

gives the file

,A,B\r
\r\n
0,1,3\r
\r\n
1,2,4\r
\r\n

however, I would like to have

,A,B\r\n
0,1,3\r\n
1,2,4\r\n

How can I achieve this (ie, \\r\\n instead of \\r\\r\\n ). My operating system is Windows 10.

The following is from a submission to Kaggle. Hope you'll find it useful. I had to write the output loop myself as pandas insisted on adding both CR and LF and it caused problems for Kaagle.

import io

with io.open('../output/submission_{}.csv'.format('22-Sep-2018-Try-Something_with_re'), 'w', newline='\n') as of:
    of.write('fullVisitorId,PredictedLogRevenue\n')
    for ind in out_log.index:
       of.write('{},{}\n'.format(ind, out_log['PredictedLogRevenue'][ind])) 

The main things to notice is the use of io.open, setting newline='\\n' in the open call, and adding '\\n' at the end of each write call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM