gpt4 book ai didi

postgresql - Postgres COPY 命令 - 带逗号的字段,用双引号引起来

转载 作者:行者123 更新时间:2023-11-29 12:33:54 27 4
gpt4 key购买 nike

我搜索并找到了一些与 postgres csv 导入相关的帖子,但没有任何内容可以解决我当前的问题。

我一直使用 postgres copy 命令将异构数据源中的数据导入我们的系统。目前正在努力处理 1 亿行的 .csv 文件,逗号分隔。问题在于这样的行:

009098,0981098094,"something","something else",""this one, well, is a problem"", "another thing"

用双引号括起来的字段,内嵌逗号。字段未正确解析,我收到错误:

"ERROR:  extra data after last expected column" 

通常出现这种情况时,我会临时处理有问题的行,但是这个文件太大了,我希望有一些更通用的方法来防御它。要求修改数据格式是不可能的。

copy mytable from '/path/to/file.csv' csv header quote '"'

最佳答案

这是格式错误的 CSV。您将双引号加倍以在引号字段中嵌入双引号;例如:

"where","is ""pancakes""","house?"

具有三个值:

  • 哪里
  • 是“煎饼”
  • 房子?

您遇到问题的行有杂散的双引号:

009098,0981098094,"something","something else",""this one, well, is a problem"", "another thing"
^^ ^^

我不认为有什么 COPY可以这样做,因为正确的版本是模棱两可的:它应该是 "this one, well, is a problem" 还是应该是 """this one, well, is a problem"""?

我认为您必须手动修复它。如果您可以唯一地识别损坏的行,一个快速的 sed 单行程序应该能够完成这项工作。


作为引用,我见过的最接近 CSV 标准的是 RFC 4180第二部分是这样说的:

5.  Each field may or may not be enclosed in double quotes (however
some programs, such as Microsoft Excel, do not use double quotes
at all). If fields are not enclosed with double quotes, then
double quotes may not appear inside the fields. For example:

"aaa","bbb","ccc" CRLF
zzz,yyy,xxx
[...]
7. If double-quotes are used to enclose fields, then a double-quote
appearing inside a field must be escaped by preceding it with
another double quote. For example:

"aaa","b""bb","ccc"

关于postgresql - Postgres COPY 命令 - 带逗号的字段,用双引号引起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13183644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com