One of the limitations of lists is that when your program terminates you lose all of the data in the list. This is the same for variables and other data structures. If you want the 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 in Python 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
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.
Writing Data To A File
Writing data to a text file
When you write data to a text file the process is quite simple. In Python you have two options for how you want to write to the file:
- ‘a’ – Append mode. This adds the data to the end of the file.
- ‘w’ – Write mode. This deletes all existing data in the file and overwrites it with the new data.
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