如何使用 cStringIO 创建具有空值的内存中 TSV 文件?
How do you create an in-memory TSV file with null values, using cStringIO?
我知道我可以制作一个简单的内存 CSV 文件,如下所示:
from cStringIO import StringIO
tsv_string = '1\t2\t3\n'
f = StringIO(tsv_string)
但是我如何调整它以包含 null
/ None
值?我问是因为我正在使用真实数据动态生成 tsv_string
。一些整数字段为空,我无法用空字符串替换它们,因为 Postgres 无法正确解释。
为了提供更多背景知识,我这样做是为了可以使用 psycopg2
的 copy_from
函数,由于上述原因,该函数目前给我这个错误:
psycopg2.DataError: invalid input syntax for integer: ""
所以问题是,如何在我的内存 TSV 文件中放置空值。是否有更合适的文件扩展名可以使用?
我从这个question.
中找到了我的答案
我必须将 null
参数指定为空字符串:
cursor.copy_from(f, 'my_table', columns=columns, null='')
我知道我可以制作一个简单的内存 CSV 文件,如下所示:
from cStringIO import StringIO
tsv_string = '1\t2\t3\n'
f = StringIO(tsv_string)
但是我如何调整它以包含 null
/ None
值?我问是因为我正在使用真实数据动态生成 tsv_string
。一些整数字段为空,我无法用空字符串替换它们,因为 Postgres 无法正确解释。
为了提供更多背景知识,我这样做是为了可以使用 psycopg2
的 copy_from
函数,由于上述原因,该函数目前给我这个错误:
psycopg2.DataError: invalid input syntax for integer: ""
所以问题是,如何在我的内存 TSV 文件中放置空值。是否有更合适的文件扩展名可以使用?
我从这个question.
中找到了我的答案我必须将 null
参数指定为空字符串:
cursor.copy_from(f, 'my_table', columns=columns, null='')