user7186
user7186

Reputation: 449

How can I place user input into a CSV file?

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

How do I write a Python dictionary to a csv file?

unfortunately printed output on each row like so:

matthew, green
rachel, blue
raymond, red

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"

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.

EDIT

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.

I also tried:

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

But this gave me: _csv.Error: sequence expected

Upvotes: 1

Views: 12232

Answers (3)

Ian Zerner
Ian Zerner

Reputation: 76

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.

EDIT

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.

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.

Upvotes: 6

kalgasnik
kalgasnik

Reputation: 3215

"unfortunately printed output on each row like so" - if I understand correctly, it's your solution

i1 = {"why": "because", "date": "sunday", "story": "blah blah blah"}
i2 = {"why": "i don't know", "date": "monday", "story": "blah blah blue"}
i3 = {"why": "third base", "date": "monday", "story": "blah blah blarg"}

keys = ("why", "date", "story")
with open('mycsvfile.csv','wb') as f:
    w = csv.DictWriter(f, keys)
    w.writeheader()
    for answer in (i1,i2,i3):
        w.writerow(answer)

Upvotes: 1

Pedro Romano
Pedro Romano

Reputation: 11213

The quoting parameter of the csv.writer controls if fields are quoted when written. If you set the value of this parameter to csv.QUOTE_ALL then all your fields will be quoted.

Upvotes: 0

Related Questions