Python adding empty rows in open with function

Viewed 182

I have a few dfs looks like that:

A    B    C    D
1    2    3    4
11   22   33   44
111  222  333  444

I tried to write they in csv file. I use:

with open(matchedLine + 'OUT', 'a') as f:
        df.to_csv(f, header=False, index = False)

And in csv i got a empty row after each row. I mean:

1 2 3 4

11 22 33 44 

etc

Why? How to delete that empty rows? What is wrong with my code?

.

2 Answers

just add the parameter : newline='' in your open function.

The line would be :

with open(matchedLine + 'OUT', 'a', newline=''):

Conformant CSV files have lines ended with "\r\n", whatever the platform to ensure easy sharing. For that reasons in Python 3, the csv library writes the end of lines, and it expects the file to be opened with newline=''.

Just write:

with open(matchedLine + 'OUT', 'a', newline='') as f:
        df.to_csv(f, header=False, index = False)
Related