Search code examples
pythoncsvexport-to-csv

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"

Solution

  • 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).