【问题标题】:How to write multiple paragraphs into one cell when writing to CSV with Python使用 Python 写入 CSV 时如何将多个段落写入一个单元格
【发布时间】:2021-11-02 08:45:42
【问题描述】:

我有 2 个变量正在使用 Python 写入 CSV。 一个变量的数据,描述,是多个段落。 如何防止新行写入新行?

from csv import writer
with open('test.csv', 'w', encoding='utf8', newline='') as file:
    thewriter = writer(file)
    header = ['Title', 'Description']
    thewriter.writerow(header)

    title = 'This is my title'
    description = 'This is my long description, with 3 paragraphs.\r\nThis is the 2nd paragrapgh\r\nAnd here the 3rd paragrapgh' 

    info = [title, description]
    print(info)
    thewriter.writerow(info)  

【问题讨论】:

  • 这个问题好像和beautifulsoup没有关系?只是 csv 在同一个单元格中插入换行符?
  • @Mahrkeenerh 你说得对,我从描述中删除了 BeautifulSoup。
  • 您可能也想从标签中删除它。然而,我的目标是让你 minimal reproductible example
  • 此问题与lxml 无关,请删除 lxml 标记 - 并使您的代码成为您在写入 csv 时遇到的问题的 minimal 示例- 您可以将多段数据作为 Python 字符串提供给csv。见minimal reproducible example
  • @balmy 感谢您的指导,我已经创建了一个简化的示例,并将继续这样做!

标签: python csv


【解决方案1】:

上面的代码正在运行。感谢cmets中的指导!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    相关资源
    最近更新 更多