pythonpandasdataframepython-3.8

Dataframe.to_csv(sep=";") ends with newline instead of ";", how to replace newline (\n)?


I have this dataframe

d = {'col1': [1, 0, 1, 1, 0, 0, 1]}
df = pd.DataFrame(data=d)

and want to turn it into a csv file with one line:

1;0;1;1;0;0;1;

I tried this:

df.to_csv("filepath/filename.csv", index=False, header=False, sep=";") 

and the result is:

1;0;1;1;0;0;1\n

How do I replace the newline with a semicolin before creating the csv file? I dont want to create, open it and then replace it.


Solution

  • You can use lineterminator (changed from line_terminator in pandas 1.5.0)

    df.to_csv("filepath/filename.csv", index=False, header=False, sep=";", lineterminator=";")