我正在尝试从我无法控制的外部系统解析 CSV 文件。
示例 CSV:
qw""erty,"a""b""c""d,ef""""g"
应该解析为:
[['qw"erty', 'a"b"c"d,ef""g']]
但是,我认为 Python 的 csv 模块不希望在单元格一开始没有用引号字符包裹时转义引号字符。
csv.reader(my_file)
(默认 doublequote=True
)返回:['qw""erty', 'a"b"c"d,ef""g']
有没有办法用 python csv 模块解析这个?
最佳答案
继@JackManey 评论后,他建议替换 '""'
的所有实例双引号内的 '\\"'
.
识别我们当前是否在双引号单元内被证明是不必要的,我们可以替换 '""'
的所有实例与 '\\"'
.
Python documentation says :
On reading, the escapechar removes any special meaning from the following character
但是,在原始单元格已经包含转义字符的情况下,这仍然会中断,例如:
'qw\\\\""erty'
生产 [['qw\\"erty']]
.所以我们也必须在解析之前转义转义字符。最终解决方案:
with open(file_path, 'rb') as f:
content = f.read().replace('\\', '\\\\').replace('""', '\\"')
reader = csv.reader(StringIO(content), doublequote=False, escapechar='\\')
return [row for row in reader]
关于python - 如何使用 csv 模块处理字段值内的双引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28725898/