Python:如何使用DictWriter将文字\ n和\ r字符写入csv文件?

时间:2020-02-05 10:31:58

标签: python json csv dictionary

  • 我正在运行Windows 10,Python 3.8.1 64位,Visual Studio代码。

我有一个脚本,该脚本通过POST请求从API获取数据。数据采用JSON格式,我首先将其保存在文本文件中。 JSON数据中包含多个表,我必须将每个表写入单独的csv文件。为此,我使用DictWriter。

import csv
import json

# This is the form of the text coming from the POST request (not actual data but it has nested 
# dictionaries and those inside lists like here in the "Laptop" list):

post_text = """{"electro": 
{
"Laptop": [{"sony": "value1",
        "apple": "value2",
        "asus": "value\n\n\r3"},
        {"sony": "value11",
        "apple": "value22",
        "asus": "value33"},
        {"sony": "HA",
        "apple": "Ha",
        "asus": "HC"}],
"Camera": [{"sony": "value4",
        "samsung": "val\r\nue5",
        "nikon" : "value6"}]
}
}"""

# Open the a text file and write post_text to it:

txt_file = open("test.txt", "w")
txt_file.write(post_text)
txt_file.close()

JSON文件(具有来自API的原始文本)还包括换行符和其他转义字符,表示\n\r

我打开JSON / txt文件以将数据写入这些csv文件中:

file0 = open("test.txt", encoding="utf-8")
json_data = json.loads(file0.read(), strict=False) # strict = False is needed for accepting the \ -characters

然后我从JSON(=字典)文件中获取所有密钥:

for k, v in json_data['electro'].items():
    tablelist.append(f'{k}')

为了使用DictWriter编写csv文件,我使用了以下脚本:

for i in tablelist:
    print("\n", "Now iterating table", i)
    for k, v in json_data["electro"][i][0].items():
        if k not in fieldlist:
            fieldlist.append(f'{k}')
            print(fieldlist)
    with open(i + '_.csv', 'w', encoding="utf-8", newline = '') as myfile:
        wr = csv.DictWriter(myfile, fieldnames = fieldlist)
        wr.writeheader()
        wr.writerows(json_data["electro"][i])
        fieldlist = []

我的问题是:

我如何将换行符和其他转义字符(特别是\ n和\ r)包括到test.txt文件以及我用DictWriter编写的每个csv文件中?到目前为止,我还是做不到这些字符在记事本/ Excel中显示为新行,我希望它们在文本(字符串)中为文字\ n:s和\ r:s。

此程序此刻将Laptop_csv写入为:

sony,apple,asus
value1,value2,"value


3"
value11,value22,value33
HA,Ha,HC

,我希望将其编写如下:

sony,apple,asus
value1,value2,value\n\n\r3
value11,value22,value33
HA,Ha,HC

1 个答案:

答案 0 :(得分:-1)

CSV模块没有提供执行此操作的机制。

一个选项可以使用repr函数对值进行转义:

>>> print('first\nsecond')
first
second
>>> print( repr('first\nsecond') )
'first\nsecond'