Python – Write “None” to a python file

Write “None” to a python file… here is a solution to the problem.

Write “None” to a python file

I have a txt file that contains multiple lines of JSON objects.
I’m parsing this file in Python, I’m writing a file where each line is a record I’m building from a JSON object (comma-separated).

Now, when I build this file – some values can be null (or None in Python). So that’s what I wrote:

a = 'abc'
b = None
str = a + "," + b
file.write(str+\n)

But I keep getting this error:
TypeError: Cast to Unicode: String or buffer required, NoneType not found

So my question is – how do I write the “null” value into a string in a file so that when I load the file into a table – the value at that location will actually be null?
How do I save this value in a file?

Thanks!

Solution

If you can have

an empty string when you have a None value, you can write:

a = 'abc'
b = None
row = a + "," + (b or "")
file.write(row + "\n")

Please do not use str as a variable name because you are hiding 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 CSV module.

With JSON, you can also have integers, lists, and dicts. To convert it to a CSV-serialized string, you can 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")

List and dict serialization is prohibited here.

Related Problems and Solutions