将列表的元素打印到 .csv 文件

发布于 2024-09-09 05:49:48 字数 100 浏览 1 评论 0原文

我正在读取 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

冷心人i 2024-09-16 05:49:48

阅读手册,有一个 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

倾城花音 2024-09-16 05:49:48

假设“row”包含字符串列表,您可以尝试使用

print ",".join(row)

Assuming that "row" contains a list of strings, you could try using

print ",".join(row)
梦魇绽荼蘼 2024-09-16 05:49:48

虽然看起来你的问题更多的是写入到一个csv文件而不是将其打印到标准输出,这里有一个使用StringIO执行后者的示例:

import StringIO
import csv

a_list_from_csv_file = [['for', 'bar'], [1, 2]]
out_fd = StringIO.StringIO()
writer = csv.writer(out_fd, delimiter='|')
for row in a_list_from_csv_file:
    writer.writerow(row)
print out_fd.getvalue()

像这样,你可以使用不同的分隔符或转义字符正如您正在阅读的 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:

import StringIO
import csv

a_list_from_csv_file = [['for', 'bar'], [1, 2]]
out_fd = StringIO.StringIO()
writer = csv.writer(out_fd, delimiter='|')
for row in a_list_from_csv_file:
    writer.writerow(row)
print out_fd.getvalue()

Like this you can use the different delimiters or escape characters as used by the csv you are reading.

喜你已久 2024-09-16 05:49:48

“线条不一定是均匀的”是什么意思?您使用的是自制 CSV 解析器还是使用 csv 模块

如果是前者并且没有什么特别的需要转义,你可以尝试类似的方法

print ",".join([ '"' + x.replace('"', '""') + '"' for x in row])

如果你不想在每个字段周围使用“”,也许可以创建一个像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

print ",".join([ '"' + x.replace('"', '""') + '"' for x in row])

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文