如何转换Python'无'输入' NULL'类型?我使用python-vertica模块查询Vertica数据库,并将结果集写入CSV文件,其中Python CSV模块将NULL作为None插入。因此,当我将此CSV文件导入Vetica数据库时,我将获得空字符串作为' '在哪里我希望它是NULL。我猜这里的问题是因为Python无类型。我该如何解决这个问题?
以下是将数据导出为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()
答案 0 :(得分:0)
如果这里的问题是你想使用NULL作为代币,只需添加一个像0.0一样的替换。
if not item:
row[index] = 'NULL'
然后更改您的副本以适应。
null as 'NULL'