You can take a look at this function that I am using to work with Hierarchical Deterministic Wallets in PyCardano. If the mnemonic file does not exist, it generates a new one and saves it to disk, and if it exists, it is using it.
def wallet_from_mnemonic(mnemonic_file: str, address_count: int = 1) -> dict:
"""Generate the wallet from a mnemonic phrase existing in a file on disk.
If the mnemonic file does not exist, generate a new mnemonic and save it.
"""
try:
with open(mnemonic_file, "r") as f:
mnem = f.read().strip()
except FileNotFoundError:
mnem = HDWallet.generate_mnemonic()
with open(mnemonic_file, "w") as f:
f.write(mnem)
hdw = HDWallet.from_mnemonic(mnem)
"""
Derive the staking key
"""
stk = hdw.derive_from_path(stake_derivation_path)
stk_skey = StakeExtendedSigningKey.from_hdwallet(stk)
stk_vkey = StakeExtendedVerificationKey.from_signing_key(stk_skey)
"""
Derive the first payment address
"""
wlts = {}
for i in range(address_count):
payment = hdw.derive_from_path(payment_derivation_path[0:-1] + str(i))
p_skey = ExtendedSigningKey.from_hdwallet(payment)
p_vkey =
PaymentExtendedVerificationKey.from_signing_key(p_skey)
p_addr = Address(p_vkey.hash(), stk_vkey.hash(), network)
wlts[i] = {
'addr': p_addr,
'skey': p_skey,
'vkey': p_vkey
}
return wlts