Skip to content

Creating a Private Key File with Python

Here is code that demonstrates how to create a private.key file with Python.

This code stores the private.key file into the current working directory. Later we show you how to store it into a default location such as ~/.config/golem-base using xdg.

First, add in the eth_account package:

pip install eth_account

Next, create a main.py with the following in it:


import os
from eth_account import Account

key_path = 'private.key'

if os.path.exists(key_path):
    print(f'File "{key_path}" already exists. Aborting.')
    exit(0)

acct = Account.create()

with open(key_path, 'wb') as f:
    f.write(bytes.fromhex(acct.key.hex()))

print('Address:', acct.address)

When you run this code with:

python wallet.py

it will create a private.key file and print out the public address, such as:

Address: 0x6a45d1092f5f6dA5F7b1B0c0e9e60EFb77e8a5F5

Using XDG to store the file in a config location

The above code stores the private.key file in the current directory or folder, essentially where you are when you run it. If you prefer to have it store it in a common config location such as ~/.config/golembase/, first add in the xdg package:

pip install PyXDG

Note: There are several python packages that provide XDG support; we opted to use this one, as it's quite popular.

Next, update the code like so; we've added comments to the two lines that need to be changed:

import os
from eth_account import Account
from xdg import BaseDirectory ## Add this line

key_path = BaseDirectory.xdg_config_home + '/golembase/private.key' ## Adjust this line

if os.path.exists(key_path):
    print(f'File "{key_path}" already exists. Aborting.')
    exit(0)

acct = Account.create()

with open(key_path, 'wb') as f:
    f.write(bytes.fromhex(acct.key.hex()))

print('Address:', acct.address)

Code Breakdown

Here's a breakdown of the code; we'll use the second example here.

  1. The eth_account package includes many useful tools for dealing with accoutns and private.key files for ethereum, especially for working with op-geth, which inclues our own fork called golembase-op-geth. The main object within this package is Account, which is what we're importing.

You can read more about the eth_account package at its official documentation site.

  1. We check if the key file already exists, and abort if so; that way we don't accidentally overwrite and existing private.key file.

  2. Next we create a new account through Account.create. This creates an account in memory, and you can easily access its Address immediately from it. The following code example shows how to do it in the Python REPL:

>>> from eth_account import Account
>>> account = Account.create()
>>> account.address
'0x408417F761725E0d0C419D045B181f542Bd3d5Bc'

Next we write the new account object to the private.key file.

And finally, we print out the address so that the user can copy it.