如何将 Python "None" 类型转换为 "NULL" 类型



如何将Python'None'类型转换为'NULL'类型?我正在使用python-vertica模块查询Vertica DB,并将结果集写入CSV文件中,其中Python CSV模块将NULL插入为None。因此,当我将此 CSV 文件导入 Vetica DB 时,我得到的空字符串为 ' ',我希望它是 NULL。我猜这里的问题是因为 Python None 类型。我该如何解决这个问题?

以下是将数据导出为 CSV 的代码:

def get_data(table, startDate, endDate, config):
connFrom = vertica_connect_from(config)
cursor = connFrom.cursor()
if startDate == endDate:
command = "select * from dev.{} where report_date='{}'".format(table,startDate)
else:
command = "select * from dev.{} where report_date between '{}' and '{}'".format(table, startDate, endDate)
cursor.execute(command)
rows = cursor.fetchall()
with open(filePath, 'w') as csvfile:
writer = csv.writer(csvfile, delimiter="|")
for row in rows:
for index, item in enumerate(row):
if (item == 0.0):
row[index] = 0
writer.writerow(row)
logger.info('Data has been copied and written to CSV file at %s', filePath)
connFrom.close()

这是我导入它的方式:

def load_data(table, config):
connTo = vertica_connect_to(config)
cur = connTo.cursor()
importCommand = "copy qa.{} from stdin null as '' rejected data '{}' exceptions '{}'".format(table,rejectedLog, exceptionLog)
with open(filePath, 'r') as fil:
try:
cur.copy(importCommand, fil)
except Exception as e:
logger.error('%s', e)
logger.info('Data has been copied, check rejected/exception files at /tmp on the destination host for any errors')
connTo.close()

如果这里的问题是您想使用 NULL 作为令牌,只需添加一个替换,就像 0.0 一样。

if not item: 
row[index] = 'NULL'

然后更改您的副本以适应。

null as 'NULL'

最新更新