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
it can be used without open as a file
import toml
data = toml.load("./config.toml")
print(data["first"]["name"])
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:
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())
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"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With