Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Reading and Writing TOML Losslessly

00:00 Read and Write TOML Losslessly. You know that tomlkit represents a TOML document using custom classes, and you’ve seen how you can create these objects from scratch and how you can read existing TOML documents.

00:12 Here you’ll load an existing TOML file and make some changes to it before writing it back to disk. Start by loading the same TOML file you used in the previous section of the course.

00:31 As you saw earlier, config is now a TOML document. You can use .add() to add new elements to it exactly as you did when you created a document from scratch.

00:46 But you can’t use .add() to update the value of existing keys. You try to lower the skill of the AI so you’ll have an easier opponent to play against, but you can’t do this with .add().

01:00 Instead, you can assign the new value as if config were a regular dictionary. When you update a value in this way, tomlkit still takes care to preserve the style and comments.

01:15 As you can see, the comment about ai_skill is left untouched. Parts of tomlkit support what’s known as a fluent interface in practice.

01:26 This means that operations such as .add() return the updated objects so you can chain another call to .add() onto it. You can take advantage of this when you need to construct tables with several fields.

01:52 Here, you create an array of tables with information about players. You start by creating an empty array of tables with the aot constructor. Then you loop over your player data to append each player to the array.

02:11 You use method chaining to create each player table. In practice, your call is .table().add().add() which adds two elements to a new table.

02:29 Finally, you add the new array of player tables at the bottom of the configuration below a short comment.

02:45 With your updates to the configuration done, you are now ready to write it back to the same file.

03:04 Open up the file and note that your updates were included. At the same time, the pre-existing style has been preserved. Note that app_name has been added, the value of user_ai_skill has been updated, and the array of [players] tables has been appended to the end of the configuration.

03:21 You’ve successfully updated the configuration programmatically while preserving all of the metadata. In the next section of the course, you’ll take a look back at what you’ve learned.

Become a Member to join the conversation.