简体   繁体   中英

Convert Bitcoin private key from file text

Good afternoon, friends, I just started learning python, I found this code that suits my needs, but on the way out everything is synchronized in one line, help me with this problem. "

import ecdsa
import hashlib
import base58


with open("my_private_key.txt", "r") as f:    #Input file path
  for line in f:

              #Convert hex private key to bytes
     private_key = bytes.fromhex(line)      

              #Derivation of the private key
     signing_key = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1)
     verifying_key = signing_key.get_verifying_key()

     public_key = bytes.fromhex("04") + verifying_key.to_string()

             #Hashes of public key
     sha256_1 = hashlib.sha256(public_key)
     ripemd160 = hashlib.new("ripemd160")
     ripemd160.update(sha256_1.digest())

             #Adding prefix to identify Network
     hashed_public_key = bytes.fromhex("00") + ripemd160.digest()

             #Checksum calculation
     checksum_full = hashlib.sha256(hashlib.sha256(hashed_public_key).digest()).digest()
     checksum = checksum_full[:4]

             #Adding checksum to hashpubkey         
     bin_addr = hashed_public_key + checksum

             #Encoding to address
     address = str(base58.b58encode(bin_addr))
     final_address = address[2:-1]

     print(final_address)

     with open("my_addresses.txt", "a") as i:
        i.write(final_address)

"

print writes a trailing newline after writing all its arguments. write does not; you have to supply it yourself.

with open("my_addresses.txt", "a") as i:
    i.write(final_address + "\n")

Or, you can use print :

with open("my_addresses.txt", "a") as i:
    print(final_address, file=i)

Ignoring many of its keyword arguments, print is defined something like

def print(*args, end='\n', sep=' ', file=sys.stdout):
    file.write(sep.join(args))
    file.write(end)
    

Also, note that you don't need to repeatedly open your output file. You can open it at the same time as the input and leave it open for the duration of the loop.

with open("my_private_key.txt", "r") as f, \
     open("my_addresses.txt", "a") as i:
    for line in f:
        ...
        print(final_address, file=i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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