如何逐行写入CSV文件? [英] How to write to a CSV line by line?
本文介绍了如何逐行写入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('\n')
OR
使用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)
OR
最简单的方法:
f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()
这篇关于如何逐行写入CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文