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  yttinyiconblue

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.

Saving data to  a text file yttinyiconblue

Saving data is easy. If you want to overwrite previously saved data use the ‘w’ parameter.


Adding to a file yttinyiconblue

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.

Non YouTube Video Links

Reading Files

Writing to files