Python writing / reading text files tutorial
One of the limitations of lists is that when you shut down you program, you lose all of the data in the list. This is the same for variables and other data structures.
If you want to data to be kept then you need to save your data to a file and load it again later. This is known as persistent data storage.
The simplest form of persistent data storage is in a text file, using the open() function.
It is great for storing:
- Variables (like strings and integers)
- Simple 1-dimensional lists (such as a shopping list)
It is not good for:
Reading data from a text file
Can’t access YouTube? Click here for the Google Drive version
Loading data from a file is easy, just specify the file using the open() command. Then read the data in to a list or variable.
Here are a few code examples for how to read from files
Saving data to a text file
Overwrite Mode ( Replace contents)
Saving data is easy. If you want to overwrite previously saved data use the ‘w’ parameter.
Append Mode (Adding to the contents)
To add to a file use the ‘a’ parameter instead of ‘w’. Don’t forget to add a newline (\n) to the end of your line, so that each item is added to a new line