简体   繁体   English

如何在每行末尾添加\\ n

[英]How do I add a \n at the end of each line

Below is my code: 下面是我的代码:

import requests

html = requests.get(

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

This produces a text file which 这将产生一个文本文件

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

I want there to be a newline right after every }, . 我希望每个},之后都有换行符。

You can "pretty print" JSON with Python's "json" module 您可以使用Python的“ json”模块“漂亮打印” JSON

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

Pretty printing: 漂亮的印刷:

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

You are receiving a JSON value without any newlines; 您正在接收没有任何换行符的JSON值; you'll have to manually insert newlines yourself: 您必须自己手动插入换行符:

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)

I replaced 'html' with 'json' in your code and improved the file handling a little (in the above code the with statement auto-closes the file object for you). 我在您的代码中将'html'替换为'json'并改善了文件处理能力(在上面的代码中, with语句自动为您关闭文件对象)。

The code uses string replacement to replace all }, strings with },\\n , effectively adding in extra newlines the original response did not have. 该代码使用字符串替换将所有},字符串替换为},\\n ,从而有效地添加了原始响应所没有的额外换行符。

Use the JSON module to pretty print: 使用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()

I would also use: 我还将使用:

html_str = html.text

As you may know, requests will decode the response to Unicode using the correct character set. 如您所知,请求将使用正确的字符集解码对Unicode的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM