Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing "None" to a file in python

Tags:

python

file

io

null

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!

like image 631
Bramat Avatar asked Sep 17 '25 21:09

Bramat


1 Answers

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.

like image 139
Laurent LAPORTE Avatar answered Sep 19 '25 10:09

Laurent LAPORTE