[英]How do I add a \n at the end of each line
下面是我的代码:
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"},
我希望每个},
之后都有换行符。
您可以使用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
}
您正在接收没有任何换行符的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)
我在您的代码中将'html'替换为'json'并改善了文件处理能力(在上面的代码中, with
语句自动为您关闭文件对象)。
该代码使用字符串替换将所有},
字符串替换为},\\n
,从而有效地添加了原始响应所没有的额外换行符。
使用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的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.