porteclefs
porteclefs

Reputation: 507

Writing for loop outputs to CSV columns

I have a for loop that prints 4 details:

deats = soup.find_all('p')
    for n in deats:
        print n.text

The output is 4 printed lines.

Instead of printing, what I'd like to do is have each 'n' written to a different column in a .csv. Obviously, when I use a regular .write() it puts it in the same column. In other words, how would I make it write each iteration of the loop to the next column?

Upvotes: 0

Views: 3673

Answers (4)

Joran Beasley
Joran Beasley

Reputation: 113948

extra_stuff = pie,cake,eat,too
some_file.write(",".join(n.text for n in deats)+"," + ",".join(str(s) for s in extra_stuff))

??? is that all you are looking for?

Upvotes: 1

Sharif Mamun
Sharif Mamun

Reputation: 3554

Hei, try like this:

import csv

csv_output = csv.writer(open("output.csv", "wb"))   # output.csv is the output file name!
csv_output.writerow(["Col1","Col2","Col3","Col4"]) # Setting first row with all column titles

temp = []
deats = soup.find_all('p')
for n in deats:
    temp.append(str(n.text))
csv_output.writerow(temp)

Upvotes: 1

shaktimaan
shaktimaan

Reputation: 12092

You use the csv module for this:

import csv
with open('output.csv', 'wb') as csvfile:
    opwriter = csv.writer(csvfile, delimiter=','
    opwriter.writerow([n.text for n in deats])

Upvotes: 1

sabbahillel
sabbahillel

Reputation: 4425

You would create the csv row as a loop (or using list comprehension) I will show the explicit loop for ease of reading and you can change it to a single list comprehension line yourself.

row = []
for n in deats:
  row.append(n)

Now you have row ready to write to the .csv file using csv.Writer()

Upvotes: 2

Related Questions