File Handling

Instruction

Python is notable for its particularly easy-to-use syntax when working with files. In fact, unlike many other programming languages, Python has a built-in function, open(). open() is used specifically for opening local files. There’s no need to import a file-handling library!

Opening a File

To open a file, you simply use the open() function:

# Open "some-file.txt" for reading
file = open("some-file.txt", "r")

In most cases, you’ll provide open() with two arguments:

  • Filename: An absolute or relative pathname for the file you want to open.
  • Mode (optional): Specifies how you want to open the file. The following modes apply to text files:

Details Parameter Mode Opens a text file for reading and writing. The file handle is positioned at the start of the file. “r+” Read+ write open() with a mode argument, it defaults to this mode. Opens a text file for reading only. The file handle is positioned at the start of the file. If you don’t provide “r” Read- only Opens a text file for writing only. The file handle is positioned at the start of the file. If the file already exists, its original contents are erased and overwritten. “w” Write- only Opens a text file for writing and reading. The file handle is positioned at the start of the file. If the file already exists, its original contents are erased and overwritten. “w+” Write+ read Opens a text file for appending (writing additional data) and reading, with the file handle positioned at the end of the file after any data it already contains. “a+” Append + read Opens a text file for appending (writing additional data), with the file handle positioned at the end of the file after any data it already contains. “a” Append- only

open() returns a file object that provides methods for reading to, writing from, and closing the specified file.

Closing a File

As you might expect, you should close a file once you’re done working with it. You do so using the file object’s close() method:

# We're done with "some-file.txt"; close it
file.close()

A Better Way to Open Files

It’s too easy to forget to close a file you’ve opened. Python addresses this by using the with statement. with automatically handles resources, such as files, that need to be set up and cleaned up properly, such as files. Instead of doing this:

# The old way
file = open(r"some-file.txt", "r")
# Perform file operations
file.close()

The with statement creates the file object and lets you define a code block:

# The newer, Pythonic way
with open(r"some-file.txt", "r") as file:
  # Perform file operations

There’s no longer any need to call the file object’s close() method. with performs all the necessary setup before entering the code block and any necessary cleanup when the block is exited.

Reading From a File

If you’ve opened a file in a mode that allows for reading from it, you can use the following file object methods to read its contents:

Details Method () character. Returns a list containing the entire contents of the file. Each element in the list is a line from the file, where a line is a string ending with a newline \n readlines() Returns a string containing the entire contents of the file. read() . • If not at the end of the file, this returns a single line from the file and updates the file handle to point to the start of the next line. • If at the end of the file, returns None readline()

You can also use a for loop to iterate through the lines in a file:

# Assume that `file` is a file object
# opened in a “read” mode
for line in file:
  print(line)

A couple of things to note about the approaches above:

  • read() and readlines() are more convenient.
  • Using readline() in a loop or for line in file: is more memory-efficient.

Writing to a File

If you’ve opened a file in a mode that allows for writing to it, you can use the following file object methods:

Details Method Takes a list of strings and writes them to the file, each as its own line. It add newline characters automatically to each string; you have to add one to the end of each string. doesn’t writelines() doesn’t Takes a string and writes it to the file. It add a newline character automatically; you have to add one to the end of the string. write()

You can also use the print() function with the optional file= parameter to write a single line to a file:

# Assume that `file` is a file object
# opened in a “write” or “append” mode
print("Here's another line.", file=file)

Unlike write() and writelines(), print() automatically adds a newline character to the end of its output.

Exception Handling

Working with files and other outside data opens the possibility of issues beyond your application’s control, from trying to access a file that was moved, deleted or had its access permissions changed to I/O errors. If your application works with external information, it must be prepared to handle exceptions.

Python’s Exception Handling Keywords: try, except, else, and finally

Python’s exception handling takes a similar approach. It uses similar keywords to those in other popular programming languages — just with Python’s syntax, and an extra keyword for performing additional actions when an exception didn’t occur:

Description Keyword try except Exception try except Exception try try exception try Marks the start of a block of code that should execute when code in theblock causes an exception: • Ifis followed by one or more subclasses of, this block’s code will execute if theblock caused the corresponding type of exception. • Ifis followed by theclass or no class at all, this block’s code will execute if theblock caused the any type of exception. Because ablock can cause more than one type of, there can be more than one except block for each. except Marks the start of a block that should execute after the,, and blocks, regardless of whether or not an exception occurred. try except else finally (optional) block. theblock, if there is one, and then theblock, if one exists. except else finally Marks the start of a block of code that might cause an exception: • If an exception occurs within this block, the rest of the code in the block is skipped, and the program’s flow jumps to the appropriate • If no exception occurs within this block, all the code in the block is executed, after which the program’s flow jumps to try Marks the start of a block that should execute if and only if theblock cause an exception. Usingto execute code if no exception occurred is rare. Ada and Ruby are the only other languages that have this feature. try else did not else (optional)

File-Related Exceptions

Here are the exceptions that you’re most likely to encounter when reading from or writing to files:

Description Exception Class Occurs when trying to access a file without proper permissions. PermissionError Occurs when trying to open a non-existent file. FileNotFoundError Occurs when trying to perform a file operation on a directory. IsADirectoryError Occurs when trying to create a file or directory that already exists. FileExistsError The base class for operating system exceptions, which includes I/O errors. Python still has anclass for backward compatibility, but in Python 3.0 and later, it’s an alias for. IOError OSError OSError Occurs when trying to perform a directory operation on something in the filesystem that isn’t a directory. NotADirectoryError

A File Exception-Handling Example

Here’s a quick exception handling example that shows all the keywords in action. Assume that the try block contains code that reads a specific file:

try:
  with open(r"programming-languages.txt", "r") as file:
    print(file.read())
except FileNotFoundError:
  print("Couldn't find the file.")
except PermissionError:
  print("You don't have permission to access the file.")
except OSError: # OSError includes I/O errors
  print("I/O error. Contact the developer.")
except Exception as e:
  print("An unexpected error occurred!")
  print(f"Error code: {e.errno}")
  print(f"Error message: {e.strerror}")
  print(f"Filename: {e.filename}")
  print(f"String representation: {str(e)}")
  print(f"Detailed representation: {repr(e)}")
  print("Contact the developer.")
else:
  print("Congratulations! No errors!")
finally:
  print("All done.")

If something in the try block causes an exception, Python starts working its way down the except blocks in order. Because of this, most except blocks are arranged in order, from most likely and specific (which is why the FileNotFoundError case is listed first) to most unlikely and general (which is why the catch-all Exception) case is listed last.

Notice that the final except block “captures” the Exception instance. The block’s code can access the Exception to display more information. You can do this with any Exception subclass.

See forum comments
Download course materials from Github
Previous: Introduction Next: File Handling Demo