I got a requirement to get data from database and write them into file with CSV format. and the further requirement is the field needs to be sepread by the comma char, and the String value needs to be enclosed with double quota char, and other fileds no need. but when write them into csv, the number field with Null value is enclosed with double quota char. below is my test code.
import csv
results = [("aaa", 123.1,323.1),("bbb",None,2345)]
with open('test.csv','w', newline='', encoding='utf-8') as csvfile:
csvwriter = csv.writer(csvfile, quotechar='"',quoting=csv.QUOTE_NONNUMERIC)
csvwriter.writerows(results)
the result after exporting is below.
"aaa",123.1,323.1
"bbb","",2345
My question is how to get the result below.
"aaa",123.1,323.1
"bbb",,2345
CodePudding user response:
Setting quoting
to csv.QUOTE_NONNUMERIC
means to quote all non-numeric values, and since None
(or ''
) is not a numeric type, its output gets quoted.
A workaround is to create a subclass of a numeric type and force its string conversion to be ''
, so that it passes csv
's numeric type check and gets a non-quoted empty output:
import csv
class empty_number(int):
def __str__(self):
return ''
EmptyNumber = empty_number()
results = [("aaa", 123.1, 323.1), ("bbb", EmptyNumber, 2345)]
with open('test.csv','w', newline='', encoding='utf-8') as csvfile:
csvwriter = csv.writer(csvfile, quotechar='"',quoting=csv.QUOTE_NONNUMERIC)
csvwriter.writerows(results)
Demo: https://replit.com/@blhsing/BurlyForthrightDatawarehouse