【问题标题】:Python loop overwrites previous text written to json filePython循环覆盖以前写入json文件的文本
【发布时间】:2018-07-20 13:58:13
【问题描述】:

我有一个执行 sql 查询并将查询输出写入 .json 文件的 python 脚本。但是,每次它为我写入 json 文件时,它都会覆盖以前写入的文本。我希望将每个 sql 查询写入一个新的单独的 .json。下面是我的代码不起作用。任何帮助将不胜感激!

from __future__ import print_function

try:
    import psycopg2
except ImportError:
    raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n')
    sys.exit(1)

import re
import sys
import json

DB_HOST = 'crt.sh'
DB_NAME = 'certwatch'
DB_USER = 'guest'
OUTPUT_DIR="output/"

def connect_to_db(domain_name):
    try:
        conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST))
        cursor = conn.cursor()
        cursor.execute("SELECT ci.NAME_VALUE NAME_VALUE FROM certificate_identity ci WHERE ci.NAME_TYPE = 'dNSName' AND reverse(lower(ci.NAME_VALUE)) LIKE reverse(lower('%{}'));".format(domain_name))
    except:
        print("\n\033[1;31m[!] Unable to connect to the database\n\033[1;m")
    return cursor


def get_unique_emails(cursor, domain_name):
    unique_emails = []
    for result in cursor.fetchall():
        matches=re.findall(r"\'(.+?)\'",str(result))
        for email in matches:
            if email not in unique_emails:
                if "{}".format(domain_name) in email:
                    unique_emails.append(email)
    return unique_emails


def print_unique_emails(unique_emails):
    print("\033[1;32m[+] Total unique emails found: {}\033[1;m".format(len(unique_emails)))
    for unique_email in sorted(unique_emails):
        print(unique_email)


if __name__ == '__main__':
    filepath = 'test.txt'
    with open(filepath) as fp:
        for cnt, domain_name in enumerate(fp):
            print("Line {}: {}".format(cnt, domain_name))
            print(domain_name)

        domain_name = domain_name.rstrip()
        cursor = connect_to_db(domain_name)
        unique_emails = get_unique_emails(cursor, domain_name)
        print_unique_emails(unique_emails)
        outfilepath = OUTPUT_DIR + unique_emails + ".json"
        with open(outfilepath, 'w') as outfile:
            outfile.write(json.dumps(unique_emails, sort_keys=True, indent=4))

【问题讨论】:

  • 使用追加而不是写入。即文件编写器中的“a”而不是“w”。
  • @sjaymj62 感谢您的帮助!如何配置我的代码以将每个查询写入单独的 .json 文件?例如,如果我查询 google.com 和 apple.com,我想要 google.com.json 和 apple.com.json 文件。非常感谢您的帮助!

标签: python sql json python-3.x


【解决方案1】:
with open(outfilepath, 'w') as outfile:
    outfile.write(json.dumps(unique_emails, sort_keys=True, indent=4))

您当前正在打开要写入的文件。您想追加到文件中。您可以通过将w 更改为a 来做到这一点

with open(outfilepath, 'a') as outfile:
    outfile.write(json.dumps(unique_emails, sort_keys=True, indent=4))

你可以阅读open()here上的文档。

【讨论】:

  • 感谢您的帮助!如何配置我的代码以将每个查询写入单独的 .json 文件?例如,如果我查询 google.com 和 apple.com,我想要 google.com.json 和 apple.com.json 文件。非常感谢您的帮助!
  • @bedford 只需将outputfilepath 的值更改为您希望调用文件的任何值。
【解决方案2】:

我认为这是因为您在编写 json 文件时没有循环,您只有一次写入,所以它只写入一个文件。所以你需要做一些你在... enumerate(fp): 时所做的事情。再做一个 for 循环,遍历每个域,然后将 OUTPUT_DIR + unique_emails + ".json" 更改为 OUTPUT_DIR + domain_name + ".json"。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2015-08-20
    • 2011-05-08
    • 1970-01-01
    • 2012-04-15
    • 2018-11-08
    • 1970-01-01
    相关资源
    最近更新 更多