How to stop writing a blank line at the end of csv file - pandas

前端 未结 4 414
南旧
南旧 2021-01-02 03:44

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 f

4条回答
  •  梦毁少年i
    2021-01-02 04:08

    For some reason, the line terminator did not work when I tried it. (It gave an error, saying line_terminator is an unrecognized keyword argument.)

    However, this will do the trick:

        df.to_csv(path)
        with open(path) as f:
            lines = f.readlines()
            last = len(lines) - 1
            lines[last] = lines[last].replace('\r','').replace('\n','')
        with open(path, 'w') as wr:
            wr.writelines(lines)
    

提交回复
热议问题