Laleh
Laleh

Reputation: 508

pandas dataframe to_csv writes blank line after each line

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?

Upvotes: 6

Views: 6658

Answers (1)

rbcvl
rbcvl

Reputation: 516

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

Upvotes: 10

Related Questions