I have to extract from several sources and save the result to csv files. When the data received for a field is None
, I want it represented as empty string. (I realize I'll lose the distinction between empty string and NULL-type values in the source.)
My underlying requirement is to preserve the distinction between the string "None" and nothingness in a plain delimited file, without using quotes.
I hope to avoid calling a function that checks if a value is null for every nullable field I write, or at least have that call not explicit in the code... eg, I want to just code f.write(row['LastName']
, and if the LastName is "None" get "None", but if it is of NoneType
get an empty string.
I haven't yet investigated if the comes-with csv library can do what I need, I will do that, it seems likely that's the easiest approach.
But: is there anything I can override, so that if I write None
to a file, I get empty string (or something besides the string "None" in the output file?
It seems to me I'd have to change either 1) the built-in write method of _io.TextIOWrapper
or 2) the __str__
method of the NoneType
.
if row['LastName'] is None
will check if your value is a NoneType
Something like:
if row['LastName'] is None:
f.write("")
else:
f.write(row['LastName'])
Would get the job done.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.