Python逐行写到CSV中

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

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文件中。 我知道我可以按照下面的思路来逐行迭代。

import StringIO
s = StringIO.StringIO(text)
for line in s:

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

EDIT---> 谢谢你的反馈,因为建议的解决方案是相当简单的,可以看到下面。

解决方案。

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

使用 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\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()
评论(5)

你可以像写任何普通文件一样写到该文件。

with open('csvfile.csv','wb') as file:
    for l in text:
        file.write(l)
        file.write('\n')

如果只是为了以防万一,它是一个列表,你可以直接使用内置的csv模块

import csv

with open("csvfile.csv", "wb") as file:
    writer = csv.writer(file)
    writer.writerows(text)
评论(0)

我将简单地把每一行写入一个文件,因为它已经是CSV格式了。

write_file = "output.csv"
with open(write_file, "w") as output:
    for line in text:
        output.write(line + '\n')

不过,我现在想不起来怎么写带断行的行了:p

另外,你可能想看看关于write()writelines()'n'这个答案

评论(0)