Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load toml file in python

Tags:

python

toml

How to load toml file into a python file that my code

python file:

import toml 


toml.get("first").name

toml file :

[first]
    name = "Mark Wasfy"
    age = 22
[second]
    name = "John Wasfy"
    age = 25
like image 231
Mark Wasfy Avatar asked Jun 10 '26 18:06

Mark Wasfy


2 Answers

it can be used without open as a file

import toml


data = toml.load("./config.toml")

print(data["first"]["name"])
like image 108
Mark Wasfy Avatar answered Jun 13 '26 19:06

Mark Wasfy


Python v3.11 onwards innately supports toml parsing via tomllib.

import tomllib

with open("file.toml", "rb") as f:
    data = tomllib.load(f)

print(data["first"]["name"])

Refer to tomllib — Parse TOML files

So:

Without installing external package

I personally prefer to not install any external packages by using the following:

Note: This uses pip. If you don't have pip available, then change the except to handle the error some other way.

try: import tomllib # Python v3.11+
except ModuleNotFoundError: import pip._vendor.tomli as tomllib # the same tomllib that's now included in Python v3.11+

def get_first_name():
    with open("pyproject.toml", "rb") as f:
        data = tomllib.load(f)
        return data.get("first", {}).get("name")

if __name__ == "__main__":
    print(get_first_name())

Using external package

Otherwise you'll have to install the toml library as mentioned in other comments with

pip install toml

and then do:

import toml

with open("file.toml", "r") as f:
    data = toml.load(f)

print(data["first"]["name"])
like image 20
Tommy Wolfheart Avatar answered Jun 13 '26 18:06

Tommy Wolfheart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!