vicky113
vicky113

Reputation: 351

Quoting in CSV from Pandas

I am working on a project where I need to manipulate certain text files and write down as text files again. A sample file will look like enter image description here

As you can see I have headers which are like "A". When I use the following code

import pandas as pd

df = pd.read_csv("Test doc.txt",sep =";")
df.to_csv("Output.txt",sep=";",index = None)

I get the output as enter image description here

Now the headers are like A, the " are gone. How do I write the file in the exact same format as before? I also tried

df.to_csv("Output.txt",sep=";",index = None, header = ["'A'","'B'","'C'"])

But this gives me enter image description here Now the header is 'A' but still not in the original format.

If I try

df.to_csv("Output.txt",sep=";",index = None, header = ['"A"','"B"','"C"'])

Now it looks like enter image description here

Upvotes: 1

Views: 177

Answers (2)

gilch
gilch

Reputation: 11651

Change the default quote char.

df.to_csv("Output.txt", sep=';', index=None, quotechar="'", header=['"A"','"B"','"C"'])

Upvotes: 1

gilch
gilch

Reputation: 11651

import csv

df.to_csv("Output.txt",sep=";", index=None, quoting=csv.QUOTE_NONNUMERIC)

Upvotes: 2

Related Questions