5.2. Writing to a File

One of the simplest ways to save data is to write it to a file. When you write text to a file, the output will still be available after you close the terminal containing your program's output. You can examine output after a program finishes running, and you can share the output files with others as well. You can also write programs that read the text back into memory and work with it again later.

Writing to an Empty File

To write text to a file, you need to call open() with a second argument 'w'. Let's write a simple message and store it in a file instead of printing it to the screen.

We use the write() method on the file object to write a string to the file. This program has no terminal output, but if you open the file programming.txt, you'll see one line.

> You can open a file in read mode ('r'), write mode ('w'), append mode ('a'), or a mode that allows you to read and write to the file ('r+'). If you omit the mode argument, Python opens the file in read-only mode by default.
> Python can only write strings to a text file. If you want to store numerical data in a text file, you'll have to convert the data to string format first using the str() function.

Writing Multiple Lines

The write() function doesn't add any newlines to the text you write. So if you write mode than one line without including newline characters, your file may not look the way you want it to.it in a file instead of printing it to the screen.

If you open programming.txt, you'll see the two lines squished together:

I like programming.I love creating new codes.

Including newlines in your calls to write() makes each string appear on its own line. You can also use spaces, tab characters, and blank line to format your output.

Appending to a File

If you want to add content to a file instead of writing over existing content, you can open the file in append mode. When you open a file in append mode, Python doesn't erase the contents of the file before returning the file object. Any lines you write to the file will be added at the end of the file. If the file doesn't exist yet, Python will create an empty file for you.

Let's modify our program by adding some texts.

> In the beginning of with block, we use the 'a' argument to open the file for appending rather than writing over the existing file. Then, we write two lines, which are added to programming.txt.

Exercise 5.2

  1. Guest
    Write a program that ask the user for their name. When they respond, write their name to a file called guest.txt.


  1. Guest Book
    Write a while loop that prompts users for their name. When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt. Make sure each entry appears on a new line in the file.


  1. Programming Poll
    Write a while loop that asks people why they like programming. Each time someone enters a reason, add their reason to a file that stores all the responses.