Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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 the 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

1 Answer

0 votes
by (106k points)

There are many ways to write into csv to file line by line:-

First thing you can do is:

##text=List of strings to be written to file 

with open('csvfile.csv','wb') as file: 

for line in text: 

file.write(line) 

file.write('\n')

OR

By using CSV writer you can write into csv:-

import csv 

with open(<path to output_csv>, "wb") as csv_file: 

writer = csv.writer(csv_file, delimiter=',') 

for line in data: 

writer.writerow(line)

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
+1 vote
1 answer
0 votes
1 answer
asked Jul 26, 2019 in Python by selena (1.6k points)
0 votes
1 answer

Browse Categories

...