使用 Python 将结果保存到 csv 文件
import csv
with open('test.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[1]] += 1
for row in data:
if counter[row[1]] >= 4:
writer = csv.writer(open("test1.csv", "wb"))
writer.writerows(row)
我得到奇怪的输出!这段代码有什么问题?
import csv
with open('test.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[1]] += 1
for row in data:
if counter[row[1]] >= 4:
writer = csv.writer(open("test1.csv", "wb"))
writer.writerows(row)
I am getting strange output! What is wrong with this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我就是这样做的
This is how I do it
这将提供准确的输出
this will provide exact output
您可以关闭文件而不是 csv.writer 对象,它应该是:
You can close files not csv.writer object, it should be:
一个简单的例子是这样的:
An easy example would be something like:
使用
csv.writer
:Use
csv.writer
:使用熊猫
Use Pandas
我知道问题是询问您的“csv”包实现,但为了您的信息,有一些更简单的选项 - 例如 numpy。
(这个答案是在 6 年后发布的,为了子孙后代。)
在与您所询问的情况类似的不同情况下,假设您有两列,如下所示:
您可以像这样保存它:
scores.csv
看起来像这样:I know the question is asking about your "csv" package implementation, but for your information, there are options that are much simpler — numpy, for instance.
(This answer posted 6 years later, for posterity's sake.)
In a different case similar to what you're asking about, say you have two columns like this:
You could save it like this:
scores.csv
would look like this: