Txt Files Writing - Lakelands Computing

Title
Go to content
Writing Text Files
When working with data outside your Python program you are going to need to store data into a file. This page looks at how to store data in a txt file. To store data you can either write it to a new file, overwrite an existing file or append the information to an existing file (add it to the end).

To overwrite file (or create new one)
  • file = open("tvShows.txt","w")

This will do one of 2 things  either open the file tvShows.txt  in write mode or if it doesn't already exist it will create the file.  Be aware that opening a file in "w" write mode will overwrite anything that is already stored in it, so be careful.

To Append to file (or create new one)
  • file = open("tvShows.txt","a")

This will also do one of 2 things  either open the file tvShows.txt in append mode or if it doesn't already exist it will create the file.  Append mode will not overwrite the data already in the file, it will add it to the end.

To write data to the file use:

  • file.write("Whatever you want to store")

This would add the string to the file. You can also use variables:

  • name = "Dave"
  • file.write(name)

and you can use For loops and Lists to write multiple items of data:

  • names =["dave","paul","alice","beth"]
  • for person in names:
    • file.write(person)

Remember to close the file
  • file.close()

Always close your files. It may cause problems if you don't with files being unavailable to read or write at a later point. Note you can avoid the need to keep closing files by using the with method. (Most experienced programmers use this)

  • with open ("tvShows.txt","w") as file:
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content