Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Examining File-Related Exceptions

Resource linked in this lesson: Python Basics: Reading and Writing Files

00:00 File handling is a major part of programming, and Python is a great tool for interacting with file systems. But there are a few exceptions you might encounter.

00:08 The FileExistsError, the FileNotFoundError, and the PermissionError. All three of these are subclasses of OSError, meaning these are errors that originate in the operating system layer.

00:20 And first, if you need a refresher on dealing with files and Python, I recommend the course Python Basics: Reading and Writing Files.

00:29 And now for a little learning by doing, follow me to the REPL.

00:34 We’ll start with FileNotFoundError. with open passing in the string ("hello.txt", And the keyword argument mode="r") as file: print(file.read()).

00:50 What this code attempts to do is open a file in the current working directory called hello.txt in read mode then print the contents of that file.

00:59 However, the result is a FileNotFoundError, no such file or directory: hello.txt. In essence, you can’t read what’s not there.

01:08 A safe way to avoid this error would be to use, you guessed it, try-except. This time try with open( "hello.txt", mode="r") as file:

01:22 print(file.read()) except FileNotFoundError: print("The file doesn't exist.")

01:35 And of course, because we didn’t at some point create this file in the past few seconds, the code in the except block runs and we see “The file doesn’t exist.”

01:45 To trigger the opposite exception, a FileExistsError, define the following function: def write_hello(): with no parameters, try: with open("hello.txt", and the keyword argument mode="x") as file: file.write passing in the string ("Hello, world!"). except FileExistsError: print ("The file already exists.")

02:19 And make sure to close all open parentheses.

02:23 The first time you run it, you should see no output. Because no error occurs, the function implicitly returns None. Call it one more time and then you see “The file already exists.”

02:38 Why does this happen? Because in this function, you’re using the mode “x” when opening the file, hello.txt, and “x” denotes creation mode. If you attempt to open a file for creation that already exists, well, it can’t be created again.

02:52 So the exception that is raised is the FileExistsError, which causes the code in the except block to run. So we see “The file already exists,”, But wait, there’s more.

03:03 We still have to see a PermissionError. The PermissionError exception is raised when Python lacks sufficient permission to perform some operation with the file system.

03:12 And depending on location and context, that could apply to writing files, modifying files, reading files. Heck, even doing the contents of a directory. So the following example will work on Unix-like systems like Linux or macOS: with open(" passing in the string /etc/hosts" And the keyword argument mode="a") as file:

03:39 print file.write("##")

03:45 And the result is a PermissionError, Permission denied: '/etc/hosts'. Because this file is a system file, it’s protected. You need root privileges to modify it.

03:57 So when Python tries to open it in append mode, which is what “a” stands for, the operating system does not like it. And that’s why you get this error, which is a good thing because you don’t really want Python scripts to be interacting with or editing sensitive system files all willy-nilly.

04:14 But of course if this code did execute successfully, it would only add two hashes, which are comment characters, to the /etc/hosts file. No harm there. Alright, so far we’ve mostly seen ways to handle exceptions and allow your programs to keep running.

04:29 Next up, you’ll see a couple examples of situations where Python applications are supposed to end. See you there.

Become a Member to join the conversation.