如何将用户输入放入CSV文件? [英] How can I place user input into a CSV file?

查看:55
本文介绍了如何将用户输入放入CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题有很多排列,但最接近的答案:

There have been a bunch of permutations of my question but the closest answer:

如何编写Python字典到csv文件?

不幸的是,每行都打印输出,如下所示:

unfortunately printed output on each row like so:

matthew, green
rachel, blue
raymond, red

其中somedict = dict(雷蒙德=红色",瑞秋=蓝色",马修=绿色")

where somedict = dict(raymond = "red", rachel = "blue", matthew = "green")

我的问题需要输出更多这样的信息:

and my problem requires output more like this:

why, date, story
"because", "sunday", "blah blah blah"

我要从用户输入中获取字典,输出文件将每个新答案(为什么,日期和故事)放在新行上也是很重要的(此外,列标题仅打印一次).所以我的代码看起来像这样:

I'm getting the dictionary from user input, and it's important that the output file places each new answer to (why, date and story) on a new line (and furthermore, that column headers are only printed once). So my code looks like this:

import csv
o = "file.csv"
why = input("Why? ")
date = input("Date: ")
story = input("Story: ") 

总而言之,我需要如下所示的输出:

And in summary, I need output that looks like this:

why, date, story
"because", "sunday", "blah blah blah"
"i don't know", "monday", "blah blah blue"
"third base", "monday", "blah blah blarg"

我只是在寻找一种简单的方法来接受用户输入,然后将其写入csv文件的新行中.我已经在这里待了大约两个小时,所以这就是为什么我在这里.首先,我遇到两个TypeError错误:(1)'str'不支持缓冲区接口(我通过在open(file,"wb","utf-8")语句中添加"utf-8"参数来解决此问题).(2)TypeError:必须为整数.由于某种原因,我从"wb"中删除了"b",并且似乎摆脱了该错误.我发布的链接使我几乎可以到达需要的位置,但还不够,我衷心感谢任何人都可以提供的任何快速说明.

I was just looking for a simple way to take user input, write it to a new line in a csv file. I've been at this for about two hours now, so that's why I'm here. First I got two TypeError errors: (1) 'str' does not support the buffer interface (which I solved by adding the "utf-8" parameter to the with open(file, "wb", "utf-8") statement). (2) TypeError: an integer is required. For some reason I took the "b" out of "wb" and it seemed to get rid of this error. The link I posted to gets me almost to where I need to be, but not quite enough and I would sincerely appreciate any quick clarification anyone can provide.

编辑

为清楚起见,我尝试了几种可能性.最有前途的是:

TO be clear, I tried a few possibilities. The most promising were:

with open("file.csv", "w", encoding = "utf-8") as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

产生了我上面引用的第一个输出,这不是我所需要的.

which produced the first output I cited above, which isn't what I need.

我也尝试过:

with open("file.csv", "w", encoding = "utf-8") as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

但这给了我:_csv.Error:预期的顺序

But this gave me: _csv.Error: sequence expected

推荐答案

如果您要做的只是接受用户输入并将其写入csv文件的新行中,则无需字典即可完成操作.在字典中执行此操作实际上取决于字典的设置-如果您对此进行更多说明,可能会有所帮助?如果这就是我的想象,卡尔加斯尼克的答案就是一个很好的答案.

If all you want to do is take user input and write it to a new line in a csv file, you can do it without a dictionary. To do it in a dictionary really depends on how the dictionary is set up - it might help if you explained a bit more about this? If it's the way I'm imagining, kalgasnik's answer is a good one.

但是偶然地不需要字典(我从您的问题中得到的一般印象),这种方式非常简单:

But on the off chance the dictionary isn't necessary (my general impression from your question), this way is pretty simple:

import csv
with open('file.csv', 'w') as f:
    w = csv.writer(f, quoting=csv.QUOTE_ALL) 

    while (1):
        why = input("why? ")
        date = input("date: ")
        story = input("story: ")
        w.writerow([why, date, story])

直接从用户输入中产生您想要的输出.

which produces the output you want directly from user input.

编辑

这种方式是为仅需一遍又一遍地输入数据而设计的,因此while(1)(永远循环).如果您想一次放入一组,请完全删除while循环-这与在末尾添加中断具有相同的效果.

That way is designed for a case where you simply take in the data over and over again, hence the while (1) (loop forever). If you want to take in sets one at a time, remove the while loop entirely - this will have the same effect as adding a break at the end.

如果您想在每次写入之间打开和关闭文件(例如,如果在两次写入之间要进行很多其他工作),那么在打开文件时,请使用"a"代替"w"来附加会将每组新的字符串写在新行上.

If you want to open and close the file between each write (for example if you will be doing a lot of other work in between), then use 'a' for append instead of 'w' when opening the file, which will write each new set of strings on a new line.

这可能是一个示例,它可能是个好主意,将所有集合存储在某个地方,然后最终将所有集合最终写入文件,因为始终打​​开和关闭文件可能会很昂贵(我不会知道这是否是您的考虑因素).如果您对字典仍然不满意,可以简单地将每个[为什么,日期,故事]列表添加到更大的列表中,然后在最终编写时在列表的最后循环.

This might be an example of when it might be a good idea to store all the sets somewhere before finally writing them all to the file at the end, because opening and closing files all the time can be expensive (I don't know if this is a consideration for you). If you are still not comfortable with dictionaries, you could simply add each [why, date, story] list into a bigger list, then loop over the list at the end when finally writing.

这篇关于如何将用户输入放入CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆