如何逐行写入CSV? [英] How to write to a CSV line by line?

查看:23
本文介绍了如何逐行写入CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有通过 http 请求访问并由服务器以逗号分隔格式发回的数据,我有以下代码:

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)

正文内容如下:

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

如何将这些数据保存到 CSV 文件中.我知道我可以按照以下方式逐行迭代:

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:

但我不确定现在如何正确地将每一行写入 CSV

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.

解决方案:

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

推荐答案

一般方法:

##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('
')

使用 CSV 编写器:

Using CSV writer :

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)

最简单的方法:

f = open('csvfile.csv','w')
f.write('hi there
') #Give your csv text here.
## Python will convert 
 to os.linesep
f.close()

这篇关于如何逐行写入CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆