【问题标题】:How to write to a CSV line by line?如何逐行写入CSV?
【发布时间】:2016-09-14 08:52:38
【问题描述】:

我有通过 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

编辑--->感谢您的反馈,建议解决方案相当简单,如下所示。

解决方案:

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

【问题讨论】:

  • 已经是 CSV 文件了,你只需要将每一行写入一个文件...
  • 老实说,我不确定您是否需要 StringIO 导入。此外,原样的解决方案可能不会分隔行,因为f.write() 不会自动附加换行符。
  • @icedwater 我明白你的意思,但我运行了上面的代码,它能够正确地将数据存储到 csv 文件中。

标签: python string file csv io


【解决方案1】:

一般方式:

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

【讨论】:

  • 对于python 3,将其更改为with open(&lt;path to output_csv&gt;, "w", newline='') as csv_file:
  • 这一行缺少信息for line in data:。请解决这个问题。谢谢。
  • @gsamaras 这个想法是为了帮助社区,不像你编辑和评论是没用的。
  • 如果csv文件中已有内容,如何追加一行,使用第三种解决方案?
  • @JürgenK。使用'a'(追加模式)代替'w'(写入模式)。
【解决方案2】:

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

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)

【讨论】:

    【解决方案3】:

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

    write_file = "output.csv"
    with open(write_file, "wt", encoding="utf-8") as output:
        for line in text:
            output.write(line + '\n')
    

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

    另外,您可能想看看this answer 关于write()writelines()'\n'

    【讨论】:

    • 也关心像这样的编码open(write_file, 'wt', encoding='utf-8')
    【解决方案4】:

    为了补充前面的答案,我开设了一个快速课程来写入 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
    

    示例用法:

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

    玩得开心

    【讨论】:

      【解决方案5】:

      这个呢:

      with open("your_csv_file.csv", "w") as f:
          f.write("\n".join(text))
      

      str.join() 返回一个字符串,它是可迭代的字符串的串联。 元素之间的分隔符是 提供此方法的字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-18
        • 2018-06-15
        • 2022-01-09
        • 2012-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多