【问题标题】:Write CSV data containing \n line breaks [duplicate]写入包含 \n 换行符的 CSV 数据 [重复]
【发布时间】:2020-11-05 15:39:54
【问题描述】:

我的 JSON 数据中的字符串可能包含“\n”换行符:

{
    "Id": 12345,
    "firstname": "Peter",
    "lastname": "Normalname"
},
{
    "Id": 76890,
    "firstname": "Paul",
    "lastname": "Evil\nLinebreak" # here's the \n
},

我正在尝试使用 Python 3 将其写入 CSV 文件。这是我的方法:

def write_csv_file(filename, resp):

    # open file
    csvFile = open(filename, "w", newline='', encoding='utf-8')
    csvWriter = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_ALL)

    # write data
    for line in resp:
       csvWriter.writerow(line.values())

    # close file
    csvFile.close()

现在我的问题是 \n 字符通过添加意外的换行符弄乱了我的 CSV 文件。

所以不是

"76890","Paul","Evil\nLinebreak"

我明白了

"76890","Paul","Evil
Linebreak"

解决此问题的最佳方法是什么,最好不更改数据,即保持 \n 字符,但不破坏 CSV 结构。

非常感谢任何提示。

【问题讨论】:

  • 你想写'\n'而不是换行符?
  • 是的@olvin-roght - 我会澄清这个问题。
  • 没有@marcin-orlowski - 正如你的帖子所暗示的,我已经将我的数据包装在“”中。
  • 这不是“搞砸” - 这是有效的引用字符串内容,包括换行符 - 任何能够读取引用的 csv 的程序都会理解它。
  • @PatrickArtner,我会收回这一点,你说的完全正确。是我正在查看的另一个错误。

标签: python json python-3.x csv


【解决方案1】:

您必须先转义反斜杠,然后才能将其放入 csv。

改变这一行

csvWriter.writerow(line.values())

进入这个

csvWriter.writerow([  s.replace('\n', '\\n') if isinstance(s, str) else s  for s in line.values()])

或转义所有使用

csvWriter.writerow([ s.encode('unicode_escape').decode() if isinstance(s, str) else s  for s in line.values()])

【讨论】:

  • 不要重新发明轮子,可以使用unicode-escape编解码器:s.encode('unicode_escape').decode()
猜你喜欢
  • 1970-01-01
  • 2016-12-08
  • 2017-04-29
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 2011-03-17
  • 2018-09-04
  • 1970-01-01
相关资源
最近更新 更多