Exploring the Different File Modes
00:00 Previously, you briefly touched on opening files in Python using either text or binary mode. In this short lesson, you’ll take a closer look at text mode and learn about even more specific constraints you can impose on text files when you open them in Python.
Recall that Python opens the specified file in text mode for reading by default. You can change this by supplying one of the valid letter codes through the
mode argument of either the
open() function or the
Also, keep in mind that text mode is implied, so you don’t have to explicitly pass the letter
t, although you can if you really want to. From now on, you’ll assume that all letter codes have that implicit
t sitting there.
Okay, here are the letter codes representing various modes for reading and writing text files in Python. The default mode is the read-only one indicated by the letter code
r, which means that your file must already exist, or else you’ll get an error when you try to open it. When the file gets opened, it’ll be positioned at the beginning, allowing you to read its contents in order.
When you use the
r+ letter code, you’ll be able to read as well as write new content to your file. While the file gets opened at the beginning, you can freely move forward or backward within the file before deciding whether to overwrite a part of it. Just as before, the file must already exist. In the write-only mode, the file may exist or it may not, in which case Python will create one for you.
That’s also why opening in write-only mode always puts you at the beginning of the file. If you want to read and write at the same time, then you can use either the
r+ mode, which you’ve already seen, or the
w+ mode. Both are very similar, but
w+ mode will either create or overwrite your file. So again, be careful when using this mode.
The next mode, denoted with a letter
a, stands for append-only. As the name implies, it’ll let you add new content at the end of the file, which is where it gets opened. Unlike in the write-only mode, you can’t freely move around within the file. Also, the file may not exist, but when it does, then the append-only mode won’t overwrite any existing content, ensuring its integrity. If you’d like to append and read the file at the same time, then use the
a+ letter code, which will let you move through the file and read its parts, but without allowing you to overwrite anything. Finally, the least common file mode is the exclusive create, which is denoted with a letter
03:00 This mode won’t let you open an existing file, and instead it’ll create a new file for you and open it in write-only mode. On the other hand, if the file already exists, then you’ll get an error.
Become a Member to join the conversation.