【问题标题】:psycopg2 issue on import csv导入 csv 时的 psycopg2 问题
【发布时间】:2018-04-26 11:28:17
【问题描述】:
def import_from_csv(common_cols_tup, table_name):
"""

:param common_cols_tup: tuple of all columns
:param table_name: database table name
:return:
"""
with open('/tmp/%s.csv'%table_name, 'r') as f:
    # Notice that we don't need the `csv` module.
    next(f)  # Skip the header row.
    dest_cur.copy_from(f, table_name, sep=";",null='\\N', columns=common_cols_tup)
dest_cur.commit()

我在尝试这段代码时得到了跟踪

文件“migrate.py”,第 29 行,在 import_from_csv dest_cur.copy_from(f, table_name, sep=";",null='\N', columns=common_cols_tup) psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error in .read() call: exceptions.ValueError 混合迭代和读取方法会丢失数据 上下文:复制 res_partner,第 1 行

【问题讨论】:

    标签: python file psycopg2


    【解决方案1】:

    关键是内部错误:

    exceptions.ValueError Mixing iteration and read methods would lose data 
    

    根据this SO response,错误来自在同一文件句柄上同时使用nextreadline。如果您使用readline 跳过我认为应该没问题的标题行。

    【讨论】:

      【解决方案2】:

      我已经解决了

      def import_from_csv(common_cols_tup, table_name):
          """
      
          :param common_cols_tup: tuple of all columns
          :param table_name: database table name
          :return:
          """
          with open('/tmp/%s.csv'%table_name, 'r') as f:
              # Notice that we don't need the `csv` module.
              next(f)  # Skip the header row.
              content = StringIO('\n'.join(line for line in f))
              dest_cur.copy_from(content, table_name, sep=";",null='\\N', columns=common_cols_tup)
          dest_cur.commit()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-12
        • 2014-10-17
        • 2011-09-08
        • 2014-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多