[Python] Python: write CSV with QUOTE_NONNUMERIC, except for None

Discussão em 'Python' iniciado por Stack, Março 19, 2025.

  1. Stack

    Stack Membro Participativo

    Given the data ['a', '', None, 5] I would like to write a CSV file as:

    "a","",,5


    If I use QUOTE_NONNUMERIC, as in:

    import csv
    with open('eggs.csv', 'w') as csvfile:
    spamwriter = csv.writer(csvfile, quoting=csv.QUOTE_NONNUMERIC)
    spamwriter.writerow(['a', None, 5])


    I get

    "a","","",5


    but if I remove the quoting=csv.QUOTE_NONNUMERIC, I get the unquoted empty string from Nona, but I also lose the quotes around the a and the empty string.

    a,,,5


    Context: I want to write files that can be read using R readr r: read_csv('eggs.csv', na=c(""), quoted_na=FALSE) that can distinguish between the empty string and missing data.

    Continue reading...

Compartilhe esta Página