简体   繁体   English

找到特定作品时在python中格式化文本文件?

[英]Format a text file in python when it finds a specific work?

I am looking to format a text file from an api request output.我希望从 api 请求输出格式化文本文件。 So far my code looks like such:到目前为止,我的代码如下所示:

import requests

url = 'http://URLhere.com'
headers = {'tokenname': 'tokenhash'}
response = requests.get(url, headers=headers,)

with open('newfile.txt', 'w') as outf:
    outf.write(response.text)

and this creates a text file but the output is on one line.这将创建一个文本文件,但输出在一行上。

What I am trying to do is:我想做的是:

  1. Have it start a new line every time the code reaches a certain word like "id","status", or "closed_at" but unfortunately I have not been able to figure this out.每次代码到达某个单词(如“id”、“status”或“closed_at”)时,让它开始一个新行,但不幸的是我无法弄清楚这一点。
  2. Also I am trying to get a count of how many "id" there are in the file but I think due to the formatting, the script does not like it.此外,我试图计算文件中有多少个“id”,但我认为由于格式的原因,脚本不喜欢它。

The output is as follows:输出如下:

{
    [
        {
            "id": 12345,
            "status": "open or close",
            "closed_at": null,
            "created_at": "yyyy-mm-ddTHH:MM:SSZ",
            "due_date": "yyyy-mm-dd",
            "notes": null,
            "port": [pnumber
            ],
            "priority": 1,
            "identifiers": [
                "12345"
            ],
            "last_seen_time": "yyyy-mm-ddThh:mm:ss.sssZ",
            "scanner_score": 1.0,
            "fix_id": 12345,
            "scanner_vulnerabilities": [
                {
                    "port": null,
                    "external_unique_id": "12345",
                    "open": false
                }
            ],
            "asset_id": 12345

This continues on one line with the same names but for different assets.这在具有相同名称但用于不同资产的一行上继续。

This code :此代码:

with open ('text.txt') as text_file :
    data = text_file.read ()
    print ('\n'.join (data.split (',')))

Gives this output :给出这个输出:

"{[{"id":12345
"status":"open or close"
"closed_at":null
"created_at":"yyyy-mm-ddTHH:MM:SSZ"
"due_date":"yyyy-mm-dd"
"notes":null
"port":[pnumber]
"priority":1
"identifiers":["12345"]
"last_seen_time":"yyyy-mm-ddThh:mm:ss.msmsmsZ"
"scanner_score":1.0
"fix_id":12345
"scanner_vulnerabilities":[{"port":null
"external_unique_id":"12345"
"open":false}]
"asset_id":12345"

And then to write it to a new file :然后将其写入新文件:

output = data.split (',')
with open ('new.txt', 'w') as write_file :
    for line in output :
        write_file.write (line + '\n')

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

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