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,820 points
5,648 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,260 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, 2019 in Python by SDeb
• 13,300 points
863 views
–1 vote
2 answers
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
1,259 views
0 votes
1 answer

How to write "not equal" in python?

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

answered Sep 18, 2018 in Python by SayantiniDeb
• 200 points
2,400 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,300 points
1,781 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,820 points
778 views
0 votes
1 answer

freopen() in python

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

answered Jan 3, 2019 in Python by anonymous
1,510 views
0 votes
2 answers

How to implement Stack in python

There are different method to implement stack ...READ MORE

answered Jun 21, 2020 in Python by pagarsach
• 160 points
1,346 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,260 points
1,961 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP