Neemaximo
Neemaximo

Reputation: 20831

Taking data from text file and writing it as a .csv file in python

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)

Upvotes: 0

Views: 2547

Answers (2)

Blender
Blender

Reputation: 298532

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)

Upvotes: 4

Israel Unterman
Israel Unterman

Reputation: 13520

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.

Upvotes: 0

Related Questions