Writing pandas DataFrame to csv file with some blank lines

I am creating a single column pandas DataFrame containing only rows. One row is empty. When I write a file to disk, an empty line gets an empty quote "", while I do not want a quote at all. Here's how to replicate the problem:

import pandas as pd
df = "Name=Test\n\n[Actual Values]\nLength=12\n"
df = pd.DataFrame(df.split("\n"))
df.to_csv("C:/Users/Max/Desktop/Test.txt", header=False, index=False)

The output file should look like this:

Name=Test
[Actual Values]

Length=12

But instead:

Name=Test
[Actual Values]
""
Length=12

Is there any way to instruct pandas not to quote and leave a blank line in the output text file? Thanks a lot.

+4
source share
1 answer

There is a parameter for DataFrame.to_csv called na_rep. If you have values None, it will replace them with what you pass into this field.

import pandas as pd
df = "Name=Test\n"
df += "\n[Actual Values]\n"
df += "Length=12\n"
df = pd.DataFrame(df.split("\n"))
df[df[0]==""] = None
df.to_csv("pandas_test.txt", header=False, index=False, na_rep=" ")

, , na_rep="" csv. , (na_rep=" "), ...

, csv "" , :

f = open(filename, 'r')
text = f.read()
f.close()
text = text.replace("\"\"","")
f = open(filename, 'w')
f.write(text)
f.close()

to_csv():

def to_csv(df, filename, separator):
    f = open(filename, 'w')
    for col in df.values:
        for row in col:
            f.write(row + separator)
    f.close()
+1

All Articles