0 votes
1 view
in Python by (47.8k 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() 


The content of the text is as follows:





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 (107k 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: 




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: 


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)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !