代码之家  ›  专栏  ›  技术社区  ›  dr_dino

如何将python的“none”类型转换为“null”类型

  •  1
  • dr_dino  · 技术社区  · 6 年前

    如何将python的“none”类型转换为“null”类型?我正在使用python vertica模块查询vertica数据库,并将结果集写入csv文件,其中python csv模块将null插入为none。因此,当我将这个csv文件导入到vetica数据库时,我得到的空字符串为',其中我希望它为空。我猜这里的问题是因为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()
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   woot    6 年前

    如果这里的问题是希望使用null作为标记,只需添加一个与0.0类似的替换项。

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

    然后把你的副本改一下。

    null as 'NULL'