Python逐行写入CSV [英] Python write to CSV line by line

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

问题描述

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

 

hdr = {'User-Agent':'Mozilla / 5.0'}
req = urllib2.Request(site,headers = hdr) site ='www.example.com'
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文件中?
我知道我可以按照以下一行进行一些迭代:

  import StringIO 
s = StringIO.StringIO(text)
在s中的行:

但是我' m不确定如何正确地将每行写入CSV



编辑--->感谢您的反馈意见,解决方案相当简单,可以在下面看到。 p>

解决方案:

  import StringIO 
s = StringIO.StringIO文本)
with open('fileName.csv','w')as f:
for s行:
f.write(line)
  ## text =要打开('csvfile.csv','wb')作为文件的文件
的字符串列表:文本中的行

file.write(line)
file.write('\\\
')

OR



使用CSV作者:

  import csv 
with open(< path to output_csv>wb)as csv_file:
writer = csv.writer(csv_file,delimiter =',')
对于数据行:
writer.writerow(行)



最简单的方式:

  f = open('csvfile.csv','w' )
f.write('hi there\\\
')#在这里给你的csv文本。
## Python将把\\\
转换为os.linesep
f.close()


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(<path to output_csv>, "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()

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

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