Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSV.QUOTE_NONNUMERIC without quoting the headers

I don't think this question has been asked before so I'd greatly appreciate it if someone could guide me in the right direction.

I'll keep it short and sweet, Is it possible to only quote the column values and keep the column headers unquoted when using CSV.QUOTE_NONNUMERIC?

docs.to_csv("test.csv", index = False, quoting = csv.QUOTE_NONNUMERIC)

Actual Output:

"id","reportname"
1,"TestReport"

Expected Output:

id,reportname
1,"TestReport"
like image 681
jcoke Avatar asked Oct 29 '25 03:10

jcoke


1 Answers

I did not found such feature in to_csv docs, thus I suggest following procedure:

import csv
import pandas as pd
df = pd.DataFrame({"id":[1],"reportname":["TestReport"]})
df[:0].to_csv("test.csv", index=False)
df.to_csv("test.csv", header=False, mode="a", index=False, quoting=csv.QUOTE_NONNUMERIC)

content of test.csv

id,reportname
1,"TestReport"

Explanation: First to_csv is used to write headers, second to write content, thus in second I specify that no header should be written (header=False) and it should append (mode="a") rather than write new file (w - default mode).

like image 160
Daweo Avatar answered Oct 30 '25 18:10

Daweo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!