如何在每行末尾添加\ n

时间:2013-11-05 19:08:28

标签: python python-2.7 newline

以下是我的代码:

import requests

html = requests.get(

html_str = html.content
Html_file= open("fb_remodel.txt",'w')
Html_file.write(html_str)
Html_file.close()

这会生成一个文本文件

{"data":[{"id":"359434924192565_361115077357883","created_time":"2013-11-05T18:52:24+0000"},{"id":"116929191671920_664658976898936","created_time":"2013-11-05T18:51:57+0000"},

我希望每个},之后都有换行符。

3 个答案:

答案 0 :(得分:3)

你可以用Python的“json”模块“漂亮地打印”JSON

请参阅:http://docs.python.org/2/library/json.html

漂亮的印刷:

import json
print json.dumps({'4': 5, '6': 7}, sort_keys=True,
...                  indent=4, separators=(',', ': '))
{
    "4": 5,
    "6": 7
}

答案 1 :(得分:2)

您收到的JSON值没有任何换行符;你必须自己手动插入换行符:

response = requests.get(...)
json_str = response.content
json_str = json_str.replace('},', '},\n')
with open('fb_remodel.txt', 'w') as json_file:
    json.file.write(json_str)

我在代码中用'json'替换了'html'并改进了文件处理(在上面的代码中with语句为你自动关闭文件对象。)

代码使用字符串替换将所有},字符串替换为},\n,有效地添加了原始响应所没有的额外换行符。

答案 2 :(得分:1)

使用JSON模块进行漂亮打印:

import json
json_pp = json.dumps(html_str, sort_keys=True,
              indent=4, separators=(',', ': '))

Html_file= open("fb_remodel.txt",'w')
Html_file.write(json_pp)
Html_file.close()

我也会用:

html_str = html.text

如您所知,请求将使用正确的字符集解码对Unicode的响应。

相关问题