5

When I write a data frame to a csv if I use the "with open", I get a blank line after each line in the csv file:

df = pd.DataFrame(data=np.random.randint(0, 100, (4, 5)), columns=list('ABCDE'))
with open('test.csv', 'a') as f:
    df.to_csv(f, header=False)

If I simply do:

df.to_csv('test.csv', header=False)

There is no blank line! What am I doing wrong?

Laleh
  • 488
  • 4
  • 16

1 Answers1

10

By default, the newline of :

with open('test.csv', 'a') as f

is \r\n

The newline in to_csv() is \n.

You can try with :

with open('test.csv', 'a', newline = '\n') as f
rbcvl
  • 406
  • 3
  • 13