Salvatore Lopiparo

Senior Software Engineer

Super Simple Python #15 – Writing to Files

This week we will learn how to write to files! Writing to files is one of the simplest and most basic ways to communicate information, either to a user or to another program (or to the program itself!).

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

This first part is easiest to do in an interactive console.

Opening a file to either read or write is very simple: use the open built-in function. To use open, we must pass two arguments: the path of the file as a string (e.g. 'C:/directory/path/file_name.txt'), which you can get from using your computers file explorer (either Windows Explorer or Finder on a Mac); and an access mode which tells the program how to open the file. There are several access modes, but the most common are 'r' for read the file, 'w' for write to file, and 'a' for append to the end of the file. We’ll be writing in our examples this lesson.

This is how we use open with a path and an access mode:

>>> f = open('C:/test_file.txt', 'w')

A couple of things happen when we execute this line.

The first thing is that when we use 'w' to gain write access, Python will lock the file path that we’ve given it, so that it has exclusive rights to the file. Until we close the file or close Python, that file cannot be modified or deleted by any other program.

The next thing to note is that we get a file object back from open. This file object is what we will use to write stuff to the file.

To close our open file, we call the close method on the file object. This will allow other programs to get access to the file. In practice, you should only keep a file open as long as you need access to it.

>>> f.close()

Note that you cannot write to a file if it has been closed! You must re-open to access it again.

There are two common methods for writing to a file: write and writelines. The first method, write, takes any string you give it and writes it directly to the file.

>>> f.write("This is a string.")
>>> f.write("Here is another string.")

If you close the file using f.close() and look at it in a text editor (PyCharm will work! Just drag it in from your file browser), you will notice that they are on the same line:

This is a string.Here is another string.

If you use the write method, you need to handle new-line characters, or \n, yourself.

>>> f = open('C:/test_file.txt', 'w')
>>> f.write("This is a string.\n")
>>> f.write("Here is another string.\n")
>>> f.close()

You should see this in the file:

This is a string.
Here is another string.

The other method, writelines, handles the \n‘s for you, but you need to pass it a list of strings.

>>> lines_to_write = ["This string will be used with 'writelines'!", "This one will too!"]
>>> f = open('C:/test_file.txt', 'w')
>>> f.writelines(lines_to_write)
>>> f.close()

Now if we check the file:

This string will be used with 'writelines'!
This one will too!

That is really all there is to writing files. The only other interesting things that are used often are the read mode 'r', and the append mode 'a'. Append mode works just like write, except when you use write or writelines, it appends the text to the end of the file, which is very useful for logging information. You should play with it! Try running the same commands in this lesson with append mode 'a' instead of write mode 'w'.

We will handle read mode next lesson.

Leave a Reply