知道如何将其读取为 CSV 吗? - Python
我有一个 CSV 文件,其格式如下:
ID=123[DLE]KEY=测试[DLE]KEY2=VAL123
其中 [DLE] 是 "数据链接escape”控制字符
知道如何将其与 csv 标准库一起使用吗?
我是否需要编辑每一行以使其兼容?
编辑:我的主要问题是“KEY=VALUE”格式
谢谢大家
I have a CSV formatted in the following way:
ID=123[DLE]KEY=test[DLE]KEY2=VAL123
where [DLE] is the "Data link escape" control character
Any idea how I could use this with the csv standard library?
Do I need to edit each row in order to make it compatible?
Edit: my main problem is the "KEY=VALUE" formatting
Thanks guys
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的数据实际上不是 CSV 格式,所以我会放弃尝试使用它。我要做的就是编写一个生成器,它获取每一行,执行
.split('\x10')
,然后执行.split('=', 1)
每一部分,然后将整个内容作为字典生成。Your data is not actually in CSV format, so I'd give up on trying to use it. What I'd do is write a generator that took each line, did
.split('\x10')
, and then did.split('=', 1)
on each piece, and then yielded the whole thing as a dict.您可以通过简单地覆盖分隔符来解析它(假设雪人是您的 DLE):
输出:
检查 csv 模块的帮助 - 任何方言参数都可以在阅读器构造函数中覆盖。
要将 KEY=VAL 解析为字典,请更改为:
输出:
You can parse it by simply overriding the delimiter (pretend the snowman is your DLE):
outputs:
Check the help for the csv module - any of the dialect parameters can be overriden in the reader constructor.
To parse your KEY=VAL into a dict, change to:
outputs:
在 Python 中,您可以向
csv
模块传递格式字符 ( csv 模块文档):In Python you can pass the
csv
module a format character (csv module docs):这就是你所追求的吗?
编辑:上面给出了更好的答案
Is this what you're after?
Edit: Better answer given above
会给你一个发电机。您可以将其转换为列表或元组。
这将是一个字典列表。
Will give you a generator. You can turn it into a list or a tuple.
Which would be a list of dicts.