How to write to CSV line by line in python

0 votes

I have data which is being accessed via http request and is sent back by the server in a comma separated format, I have the following code :

site= 'www.example.com'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
soup = soup.get_text()
text=str(soup)

The content of text is as follows:

april,2,5,7
may,3,5,8
june,4,7,3
july,5,6,9

How can I save this data into a CSV file. I know I can do something along the lines of the following to iterate line by line:

import StringIO
s = StringIO.StringIO(text)
for line in s:

But i'm unsure how to now properly write each line to CSV

Nov 15, 2018 in Python by Jino
• 5,560 points
330 views

1 answer to this question.

0 votes

The simple way of doing this will be as follows:

import StringIO
s = StringIO.StringIO(text)
with open('fileName.csv', 'w') as f:
    for line in s:
        f.write(line)

answered Nov 15, 2018 by findingbugs
• 3,170 points

Related Questions In Python

0 votes
1 answer

How to read a large file, line by line, in Python?

The correct, fully Pythonic way to read ...READ MORE

answered Jul 1 in Python by SDeb
• 13,160 points
29 views
0 votes
1 answer
0 votes
1 answer

How to add a new line in Python?

You can use '\n' for a next ...READ MORE

answered May 2, 2018 in Python by aayushi
• 750 points
105 views
0 votes
1 answer

How to write "not equal" in python?

The keywords is and is not are ...READ MORE

answered Sep 17, 2018 in Python by SayantiniDeb
• 200 points
112 views
0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 13,160 points
123 views
0 votes
1 answer

Open file in Python

There is this code I used for ...READ MORE

answered Nov 16, 2018 in Python by Jino
• 5,560 points
33 views
0 votes
1 answer

freopen() in python

sys.stdout is simply file object, so, you ...READ MORE

answered Jan 3 in Python by anonymous
127 views
0 votes
1 answer

How to implement Stack in python

class Stack: def __init__(self): ...READ MORE

answered Nov 15, 2018 in Python by findingbugs
• 3,170 points
38 views
0 votes
1 answer

How to do Matrix Multiplication in python?

def matmult(a,b): zip_b = ...READ MORE

answered Nov 15, 2018 in Python by findingbugs
• 3,170 points
263 views