簡體   English   中英

Python遍歷文件數據並輸出

[英]Python looping through file data and outputting

我需要一些代碼來攝取包含電子郵件的文件,並與“ haveibeenpwned” API進行交互以返回在公共轉儲中看到它們的日期。

到目前為止,這是我下面的內容,而我目前正在努力實現以下目標:

1.)根據API使用指南,每個請求必須延遲1秒。

2.)腳本必須包含一個文件,其中將包含要提交的電子郵件(我嘗試在命令行上使用for循環調用它,但這沒有用)。

3.)提交的電子郵件地址必須回顯到輸出文件中,以便與違規數據關聯。

本質上,我希望運行腳本,提供一個輸入文件(可能帶有argparse),然后讓腳本將以下示例內容輸出到文件,並在通過提供的電子郵件列表運行時將其追加...

email1@email.com

數據-在xxxx-xx-xx上違反

email2@email.com

數據-在xxxx-xx-xx上違反

任何幫助或建議與所需的更改將不勝感激。 您可以通過使用--a運行它並提供一個電子郵件地址來查看其當前功能。

import argparse
import json
import requests


def accCheck(acc):
    r = requests.get(
            'https://haveibeenpwned.com/api/v2/breachedaccount/%s?truncateResponse=false' % acc
        )
    data = json.loads(r.text)
    for i in data:
        print(
            i['Name'] +
            ' - Breached on ' +
            i['BreachDate']
        )

def list():
    r = requests.get(
            'https://haveibeenpwned.com/api/v2/breaches'
        )
    data = json.loads(r.text)
    for i in data:
        print(
            i['Name'] +
            ' - Breached on - ' +
            i['BreachDate']
        )

if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument(
        '-a',
        '--account'
    )
    ap.add_argument(
        '--list',
        action='store_true'
    )
    args = ap.parse_args()
    acc = args.account
    list = args.list
    if not list:
        if not acc:
            print(
                'Specify an account (-a <email>) to check or --list for site info'
            )
            exit(0)
        try:
            accCheck(acc)
        except ValueError:
            print(
                'No breach data found'
            )
    else:
        list()

您可以將輸入文件和輸出文件作為命令行參數接受,如下所示:

ap.add_argument(
    '-if',
    '--input_file'
    )

ap.add_argument(
    '-of',
    '--ouput_file'
    )
args = ap.parse_args()

input_file = args.input_file

ouput_file = args.ouput_file

假設您指定為輸入文件的文件在每一行中都包含一個電子郵件帳戶,則可以執行以下操作:

with open(input_file,'r') as fl,RedirectStdoutTo(ouput_file):
        for acc in fl:
            try:
                accCheck(acc.rstrip())
            except ValueError:
                print(
                    'No breach data found'
                )

RedirectStdoutTo是您將要編寫的類,以允許您將打印輸出重定向到文件

class RedirectStdoutTo:
    def __init__(self, filename):
        self.out_new = open(filename,'w')

    def __enter__(self):
        self.out_old = sys.stdout
        sys.stdout = self.out_new

    def __exit__(self, *args):
        sys.stdout = self.out_old
        self.out_new.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM