-1

I am trying to clean a csv file that I downloaded from google sheets. But my output when I write it to a new csv file has the rows separated

code:

with open(output_file, 'w') as new_file:
    writer = csv.writer(new_file)
    writer.writerow(["Name", "Id", "Agent", "WinLoss", "Fees",
                     "Rakeback", "Rebate", "Net"])
    for row in reader:
        fees = row["Total"]
        total_rebate = rebate(row["Winning+fees"], rebate_rate)
        winloss = get_winnings(row["Winning+fees"], row["Total"])
        rakeback = calculate_rakeback(fees)
        net = calculate_net(winloss, total_rebate, rakeback)
        writer.writerow([row["Player Name"], row["Player ID"], row["Agent Name"], winloss,
                         fees, rakeback, total_rebate, net])

    new_file.close()

screenshot of output

1 Answers1

0

The problem is that the standard windows line seperator \r\n is written to the csv file in text mode. But then the Python runtime replaces the \n with \r\n so that in the end the file containt \r\r\n at every line break, hence the extra line.

To solve this problem set the lineterminator attribute when creating the writer:

writer = csv.writer(new_file, lineterminator='\n')

You can read more about the problem in this thread.

Edit

As noted by Mark Tolonen the recommended way to go about this would be to add newline='' in the open statement, so with open(output_file, 'w', newline='') as new_file:

Also see the csv documentation for more info.

Owl Surojit
  • 173
  • 1
  • 10