python逐行写入csv,Python逐行写入CSV

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

EDIT---> Thanks for the feedback as suggested the solution was rather simple and can be seen below.

Solution:

import StringIO

s = StringIO.StringIO(text)

with open('fileName.csv', 'w') as f:

for line in s:

f.write(line)

解决方案

General way :

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

Using CSV writer :

import csv

with open(, "wb") as csv_file:

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

for line in data:

writer.writerow(line)

OR

Simplest way:

f = open('csvfile.csv','w')

f.write('hi there\n') #Give your csv text here.

## Python will convert \n to os.linesep

f.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值