0

EDIT: Thanks for the answers guys, got what I needed!!

Basically I am trying to take what I have stored in my textfile and I am trying to write that into a .csv file. In my file are tweets that I have stored and I am trying to have one tweet in each cell in my .csv file.

Right now it is only taking one tweet and creating a .csv file with it and I need it to take all of them. Any help is greatly appreciated. Here is what I have so far.

with open('reddit.txt', 'rb') as f:
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
for row in reader:
    print row


    cr = csv.writer(open('reddit.csv', 'wb'))
    cr.writerow(row)
1
  • 3
    You're clobbering reddit.csv with every row. You should open it before the for loop. Don't forget to close it after the loop. Commented Dec 10, 2012 at 5:55

2 Answers 2

4

You'll need to create the writer outside of the loop:

with open('reddit.txt', 'rb') as input_file:
    reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)

    with open('reddit.csv', 'wb') as output_file:
        writer = csv.writer(output_file)

        for row in reader:
            writer.writerow(row)

Although here it might be cleaner to open the files without with:

input_file = open('reddit.txt', 'rb')
output_file = open('reddit.csv', 'wb')

reader = csv.reader(input_file, delimiter=':', quoting=csv.QUOTE_NONE)
writer = csv.writer(output_file)

for row in reader:
    writer.writerow(row)

input_file.close()
output_file.close()

Or you can still use with and just have a really long line:

with open('reddit.txt', 'rb') as input_file, open('reddit.csv', 'wb') as output_file:
    reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
    writer = csv.writer(output_file)

    for row in reader:
        writer.writerow(row)
Sign up to request clarification or add additional context in comments.

2 Comments

In 2.7/3.x, you could do with open('reddit.txt', 'rb') as input_file, open('reddit.csv', 'wb') as output_file: to get a little less indentation going (though the line is kind of long). I do think it's worth having it in the with even if the indentation is kind of annoying, just for the guaranteed correct behavior on closing.
@Dougal: Yeah, I'm not sure if having a really long line is better or worse than having a deeply nested block. I'll add that in as well.
0

The line cr = csv.writer(open('reddit.csv', 'wb')) is inside the for loop. You need to open the file just once, place this line after

reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)

Then write to it as you did in each loop iteration.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.