An Introduction to Programming

Python for All

Chapter Eleven — Reading and Writing Text Files

Thanasis Troboukis  ·  All Chapters

Chapter Eleven

Reading and Writing Text Files

Variables disappear when your program stops. Files let you save text so you can open it again later.

What Is a File Path?

A file path is just the location of a file. When you write "notes.txt", Python looks for a file called notes.txt in the current folder.

Path Meaning
"notes.txt" A text file in the same folder as your program.
"data/notes.txt" A file inside a folder called data.
"todo.txt" Another simple file name. The .txt ending means plain text.
Keep it simple: when you are starting out, save the file in the same folder as your script and use a short path like "notes.txt".

Saving Text with open()

To save text to a file, use open(path, mode). The path is the file name. The mode tells Python what you want to do with the file.

Python · Try it — save a text file

      

file.write(...) sends text into the file. file.close() closes the file so Python finishes saving it.

You can also write files with with open(...). This is a shorter pattern that closes the file automatically when the block ends.

Python · Try it — save with with open()

      
Important: opening a file in "w" mode will overwrite the old contents. With with open(...), you do not need to write file.close().

Opening and Reading a Text File

To read a file, open it in "r" mode and then use .read().

Python · Try it — read a text file

      

.read() returns the whole file as one string. If the file has line breaks, they come back inside that string too.

You can read a file with with open(...) too.

Python · Try it — read with with open()

      

Appending More Text

If you want to add text without deleting what is already there, use "a" mode.

Python · Try it — append to a file

      

The second line is added at the end because the file was opened in append mode.

Your Turn

Create a file called journal.txt. Save three lines of text into it, then open it again and print the contents.

Python · Your solution

      
Congratulations — you have completed Book 1. You now know variables, strings, lists, dictionaries, booleans, functions, regex basics, and simple file handling with open(). That is a strong base for everything that comes next.

Chapter Navigation

Move between chapters.

Loading Python environment — this may take a moment…