Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 写入包含换行符的CSV数据\n_Python_Json_Python 3.x_Csv - Fatal编程技术网

Python 写入包含换行符的CSV数据\n

Python 写入包含换行符的CSV数据\n,python,json,python-3.x,csv,Python,Json,Python 3.x,Csv,我有JSON数据,其中的字符串可能包含“\n”换行符: { "Id": 12345, "firstname": "Peter", "lastname": "Normalname" }, { "Id": 76890, "firstname": "Paul", "lastname&qu

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

{
    "Id": 12345,
    "firstname": "Peter",
    "lastname": "Normalname"
},
{
    "Id": 76890,
    "firstname": "Paul",
    "lastname": "Evil\nLinebreak" # here's the \n
},
我正在尝试使用Python3将其写入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"
我明白了

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


非常感谢您的任何提示。

在将反斜杠放入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()])


你想写
'\n'
而不是换行吗?是@olvin roght-我会澄清这个问题。不@marcin orlowski-正如你的帖子所建议的,我已经在用“”包装我的数据了。这不是“乱七八糟的”-这是有效的引用字符串内容,包括换行符-任何能够读取引用的csv的程序都会理解它。@PatrickArtner,我收回这句话,你完全正确。是我看到的另一个错误。不要重新发明轮子,您可以使用编解码器:
s.encode('unicode_escape')。decode()
csvWriter.writerow([ s.encode('unicode_escape').decode() if isinstance(s, str) else s  for s in line.values()])