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

前端 未结 4 410
南旧
南旧 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条回答
  • 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)
    
    0 讨论(0)
  • 2021-01-02 04:23

    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="")
    
    0 讨论(0)
  • 2021-01-02 04:23
    file_out = r'c:\your_output_file_path\file_name.csv'
    df.to_csv(file_out)
    file_data = open(file_out, 'rb').read()
    open(file_out, 'wb').write(file_data[:-2])
    

    df.to_csv() function has a parameter called line_terminator with a default value of '\n'. This new line character is the issue at hand.

    The code above:
    1) writes the dataframe to file as normal
    2) opens the file and reads in the bytes data to the file_data variable
    3) writes the file_data variable back out to the same file but trims off the '\n' with the splice: file_data[:-2]

    0 讨论(0)
  • 2021-01-02 04:25

    A more efficient way is to open the file first, write to that stream, then remove the last newline:

    import os
    with open('csv_data', 'wb') as dst:
        data.to_csv(wb, sep=',', encoding='utf-8', header= False, index = False)
        dst.seek(-1, os.SEEK_END) # <---- 1 : len('\n')
        dst.truncate()
    
    0 讨论(0)
提交回复
热议问题