File Handling

Opening External Files

If we ever want to create input and output somewhere other than the console, one way we can do that is by opening external files that we can use to read from, append to, and write to. 

The key function for working with files in Python is the open() function. This takes in two parameters: filename and mode. There are four different modes for opening a file:

  • “r” – Read – Default value. Opens a file for reading, error if the file does not exist
  • “a” – Append – Opens a file for appending, creates the file if it does not exist
  • “w” – Write – Opens a file for writing, creates the file if it does not exist
  • “x” – Create – Creates the specified file, returns an error if the file exists

Reading From Files

For instance, if I had file called “demofile.txt” stored in the same folder as the Python file I am running, I could read from that file like so:

					f = open("demofile.txt", "r")

text = f.read()


A few additional things to notice in the code above: first, it is a good practice to always close the file when you are done with it by using the close() function. This prevents the the risk of being unwarrantedly modified or read.

Second, we see the read() function used to extract the entire text contents from the file. To isolate more specific parts of the file, we could utilize the readline() function, which extracts the current line as you parse through the file, or the readlines() function, which returns a list containing each line of the file as an individual element.

For example, say I had a file called roster.txt containing the players on a team:

					Lebron James
Kevin Durant
Stephen Curry
Nikola Jokic
Giannis Antetokounmpo


We could create a list of each of these names by doing the following from a Python file:

					f = open("roster.txt", "r")

lineup = f.readlines()

# will print "["Lebron James", "Kevin Durant", "Stephen Curry", "Nikola Jokic", "Giannis Antetokounmpo"]


Keep in mind also that read mode (“r”) is the default value, so if no mode is passed as a parameter it will automatically be in read mode.

Additionally, if you try to open a file in read mode that does not exist in the folder, you will receive a FileNotFoundError.

Writing To Files

There are two ways that we can write from a Python program to an external file by using either the append (“a”) or write (“w”) mode. The difference between these two is that appending to a file will allow you to add text to the end of what already exists in the file, while writing to a file will overwrite what already exists. Both modes primarily utilize the write() function in order to add text to the file.

In both of these cases, if the filename passed does not exist in the folder, it will be created as a blank document. 

Here is an example of adding players to the roster.txt file above:

					# open the file in append mode:
f = open("roster.txt", "a")

# add several new players on a new line to the file:
f.write("\nJimmy Butler")
f.write("\nDame Lillard")
f.write("\nJoel Embiid")


The contents of the roster.txt file should look like this now:

					Lebron James
Kevin Durant
Stephen Curry
Nikola Jokic
Giannis Antetokounmpo
Jimmy Butler
Dame Lillard
Joel Embiid


Alternatively, if we wanted to completely overwrite the roster.txt file with brand new players, we would need to use the write mode (“w”). See the code below:

					# open the file in write mode:
f = open("roster.txt", "w")

# add brand new players to the file
f.write("Tim Duncan")
f.write("\nShaquille O'Neal")
f.write("\nMichael Jordan")
f.write("\nKobe Bryant")
f.write("\nPaul Pierce")


The roster.txt file would now look like:

					Tim Duncan
Shaquille O'Neal
Michael Jordan
Kobe Bryant
Paul Pierce

Creating and Deleting Files

We can create brand new files using the create mode (“x”). If the file already exists when we try to do this, we will receive a FileExistsError. See the code below to create a brand new blank document called highscores.txt:

					# create a new empty file:
f = open("highscores.txt", "x")


To delete a file, we need to import the OS module, and run its os.remove() function:

					import os

We will explore the OS module a bit more in a later lesson.

Replit Practice