将列表的元素打印到 .csv 文件
我正在读取 csv 文件并将每一行作为列表处理。最后,我想重新打印到 .csv 文件,但行不一定是均匀的。显然我不能直接“打印行”,因为这会将其打印为列表。如何以 .csv 格式打印它?
I am reading in a csv file and dealing with each line as a list. At the end, I'd like to reprint to a .csv file, but the lines aren't necessarily even. I obviously cannot just go "print row"
, since this will print it as a list. How can I print it in .csv format?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
阅读手册,有一个 CSV 编写方法(也有示例)。不要打印数据,存储它们,然后将它们写入 CSV 文件
http:// /docs.python.org/library/csv.html#csv.writer
Read manual, there's a CSV writer method (with example too). Don't print the data, store them and then write them into CSV file
http://docs.python.org/library/csv.html#csv.writer
假设“row”包含字符串列表,您可以尝试使用
Assuming that "row" contains a list of strings, you could try using
虽然看起来你的问题更多的是写入到一个csv文件而不是将其打印到标准输出,这里有一个使用StringIO执行后者的示例:
像这样,你可以使用不同的分隔符或转义字符正如您正在阅读的 csv 所使用的。
Though it looks like your question was more towards writing to a csv file rather than printing it to standard output, here an example to do the latter using StringIO:
Like this you can use the different delimiters or escape characters as used by the csv you are reading.
“线条不一定是均匀的”是什么意思?您使用的是自制 CSV 解析器还是使用 csv 模块?
如果是前者并且没有什么特别的需要转义,你可以尝试类似的方法
如果你不想在每个字段周围使用“”,也许可以创建一个像
escape_field()
这样的函数来检查它是否需要用双引号括起来和/或转义。What do you mean by "the lines aren't necessarily even"? Are you using a homebrew CSV parser or are you using the csv module?
If the former and there's nothing special you need to escape, you could try something like
If you don't want ""s around each field, maybe make a function like
escape_field()
that checks if it needs to be wrapped in double quotes and/or escaped.