It might be better to take a file path as input, and have the script output the keys to that particular file path. If the intended use is for the script to output to a txt file, there shouldn't be the potential for it to output to the console output.
Input file path and filename are taken.
This is nonsense to always write to a file and put that in code to take output filename always, like you can always redirect the output with > sign.
Now you have two possible options to choose from - print to screen or print to a file.
EDIT:
I am pasting last version from me of keyhunter, it is made to produce WIF + '_0' (space) which is format to directly import to a wallet.
#!/usr/bin/python3
import binascii
import os
import hashlib
import sys
import base58
readlength=10*1024*1024
magic = b'\x01\x30\x82\x01\x13\x02\x01\x01\x04\x20'
magiclen = len(magic)
def b58c(hex):
return base58.b58encode_check(hex)
if len(sys.argv) != 2:
print("./{0} <filename>".format(sys.argv[0]))
exit()
with open(sys.argv[1], "rb") as f:
while True:
data = f.read(readlength)
if not data:
break
pos = 0
while True:
pos = data.find(magic, pos)
if pos == -1:
break
key_offset = pos + magiclen
key_data = b"\x80" + data[key_offset:key_offset + 32]
print(b58c(key_data).decode('utf-8')+' 0')
pos += 1
if len(data) == readlength:
f.seek(f.tell() - (32 + magiclen))