Reputation: 997
I have a txt file that contains rows of JSON objects. I'm parsing this file in Python, and I'm writing a file that every row in it will be a record (Comma separated) I've built from the JSON object.
Now, when I'm building this file - some of the values can be Null (or None in Python). So this is what I write:
a = 'abc'
b = None
str = a + "," + b
file.write(str+\n)
But I keep getting this error:
TypeError: coercing to Unicode: need string or buffer, NoneType found
So my question is - How can I write "Null" values into the file, in a string, so when I load the file into the table - the value in that position will actually be Null? How can I keep this value in a file?
Thank you!
Upvotes: 4
Views: 9273
Reputation: 22962
If it's Ok for you to have an empty string when you have None
value, you can write:
a = 'abc'
b = None
row = a + "," + (b or "")
file.write(row + "\n")
Please, don't use str
as a variable name because you shadow a built-in function/class
Or more generally, if you have a list of items:
items = ['abc', None]
row = [(item or "") for item in items]
file.write(",".join(row) + "\n")
Or use the CSV module.
With JSON, you could also have integers, list
and dict
. To convert that in string for a serialization in CSV, you could use:
def to_string(obj):
if obj is None:
return ""
elif isinstance(obj, (list, dict)):
raise TypeError(repr(type(obj)))
else:
return str(obj)
row = [to_string(item) for item in items]
file.write(",".join(row) + "\n")
Here, list
and dict
serialization is prohibited.
Upvotes: 2
Reputation: 402603
Use str.format
.
a = 'abc'
b = None
file.write("{},{}\n".format(a, b))
The error you get is in the line above file.write
. When concatenating items to form a string, all items being concatenated must also be a string. This would mean, you'd need to do something along the lines of:
string = a + ',' + str(b)
file.write(string + '\n')
It is worth noting that you shouldn't use str
, dict
, or list
to name variables as it shadows the inbuilt classes with the same name.
You might also consider using NaN
, or, as mentioned just have an empty string ""
instead of None
. Furthermore, look into the csv
module on how to write to a CSV file. Here's an example from the csv
documentation:
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',')
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Upvotes: 2