Skip to content
Learnearn.uk » A Level Computer Science Home » Writing Data to TXT Files

Writing Data to TXT Files

Introduction

Introduction

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

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.

#Open a file and print out all the contents.

f = open("myfile.txt","r")
for line in f:
    print("line)

#Read one line from the file and save it to a variable.

f = open("highscore.txt","r")
score = f.readline()

#Read the whole file in to a list.

f = open("shopping.txt","r")
shoppingList = []
for line in f:
    shoppingList.append(line)

 

Tutorial Video


Can’t access YouTube? Click here for the Google Drive version

 

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.

#Here we try to append to the weights.txt file. If it doesn't exist we create it instead.

try:
    f = open('weights.txt',"a")  #To append(add) to  a file we use "a" instead of "w"
except:
    f = open('weights.txt',"w")


weight = input("How much do you weigh this week (Kgs)?")
#We need to add the newline character (\n) so that each weight is added to a new line.
f.write(weight + "\n") 

f.close() #This line is important! The file won't save until you do this!

print("We have added "+weight+"Kg to the file.")

Tutorial Video

Can’t access YouTube? Click here for the Google Drive Version

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

 

Resources