【问题标题】:How do I add a \n at the end of each line如何在每行末尾添加一个 \n
【发布时间】:2013-11-05 19:08:27
【问题描述】:

下面是我的代码:

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 python-2.7 newline


    【解决方案1】:

    您可以使用 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
    }
    

    【讨论】:

      【解决方案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)
      

      我在您的代码中将“html”替换为“json”并稍微改进了文件处理(在上面的代码中,with 语句会自动为您关闭文件对象)。

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

      【讨论】:

      • 危险,威尔罗宾逊。如果 }, 出现在字符串中,这也会替换它。这显然不是 OP 的数据集的问题,但通常可能是一个问题。
      • @Robᵩ:确实如此;您可以使用 json 解析 JSON 并使用更多空格将其写出,但这在这里似乎有点过头了。
      【解决方案3】:

      使用 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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-10
        • 2016-01-03
        • 2017-03-21
        • 1970-01-01
        • 2021-12-28
        • 2015-02-16
        • 2013-04-05
        相关资源
        最近更新 更多