Reading and Writing

In our last lesson we learned how to read files, now we’ll start writing them back.

We’re going to build on the last lesson by reading out the old text, and adding some new text.

We start with the file name, open for reading with the ‘r’ argument. Again, we print out the contents of the file as it was with print current_contents

write_text becomes the file handle, we’re opening the file for writing with w. This will overwrite the contents. There are options which will open for append, saving the existing contents however for this demo I thought we’d manually open for reading and add the current_contents back to the start of the file.

As you’ll see, every time you run the program you’ll get an additional line with “I feel happy!”

Run a few more times and it will keep going!

 

Python has a number of different file modes:

Questions