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

编辑—>感谢您的反馈build议解决scheme是相当简单,可以看到下面。

解:

 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编写器:

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

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

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

我不记得现在如何用换行符写行,但是:p

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

你可以写入文件,就像你写任何普通文件一样。

 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)