Python逐行写入CSV

Mus*_*ger 78 python csv string io file

我有通过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)
Run Code Online (Sandbox Code Playgroud)

文字内容如下:

april,2,5,7
may,3,5,8
june,4,7,3
july,5,6,9
Run Code Online (Sandbox Code Playgroud)

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

import StringIO
s = StringIO.StringIO(text)
for line in s:
Run Code Online (Sandbox Code Playgroud)

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

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

解:

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

Ani*_*non 144

一般方式:

##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')
Run Code Online (Sandbox Code Playgroud)

要么

使用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)
Run Code Online (Sandbox Code Playgroud)

要么

最简单的方法:

f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()
Run Code Online (Sandbox Code Playgroud)

  • 对于python 3,将其更改为`with open(<path to output_csv>,"w",newline ='')为csv_file:` (13认同)
  • @尤尔根K。使用“a”(追加模式)代替“w”(写入模式)。 (6认同)
  • 缺少此行的信息`for line in data:`。请解决这个问题。谢谢你。 (3认同)

Vis*_*hwa 13

您可以像写入任何普通文件一样写入文件.

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

如果以防万一,它是一个列表列表,您可以直接使用内置csv模块

import csv

with open("csvfile.csv", "wb") as file:
    writer = csv.writer(file)
    writer.writerows(text)
Run Code Online (Sandbox Code Playgroud)


ice*_*ter 7

我只想将每一行写入文件,因为它已经是CSV格式:

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

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

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


jrm*_*jrm 6

为了补充之前的答案,我创建了一个快速课程来写入 CSV 文件。如果您必须处理多个文件,它可以更轻松地管理和关闭打开的文件,并实现一致性和更清晰的代码。

class CSVWriter():

    filename = None
    fp = None
    writer = None

    def __init__(self, filename):
        self.filename = filename
        self.fp = open(self.filename, 'w', encoding='utf8')
        self.writer = csv.writer(self.fp, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL, lineterminator='\n')

    def close(self):
        self.fp.close()

    def write(self, elems):
        self.writer.writerow(elems)

    def size(self):
        return os.path.getsize(self.filename)

    def fname(self):
        return self.filename
Run Code Online (Sandbox Code Playgroud)

用法示例:

mycsv = CSVWriter('/tmp/test.csv')
mycsv.write((12,'green','apples'))
mycsv.write((7,'yellow','bananas'))
mycsv.close()
print("Written %d bytes to %s" % (mycsv.size(), mycsv.fname()))
Run Code Online (Sandbox Code Playgroud)

玩得开心