Lesson 12: Files and Exceptions in Python

Learn python programming in 12 lessons


You have probably already guessed that computer programs have the ability to write and read data to files. Files are identified by their unique filename which is why you don’t find the exact same filename in the same location.

There are two type of files that you will one across
Text files: strings terminated by a new line
Binary files: are not text files and store information as encoded by the application
Note that every text file is a binary file but every binary is not a text file.

Opening and closing files in Python

The syntax used to open a file is <file> = open (<filename>,<mode>)
To close the file, simply use <file>.close()
<file> represents a Python variable and <mode> can be either
  • r: to read only
  • w: to write
  • a: to append
There are 4 more other that you can read about here

f = open (“fileOne.txt”,”r")
The above syntax opens a file called fileOne.txt to read its contents. To read the content of the file, you can use either one of the following
f.read() —> reads the entire files in and stores it as one string
f.readline() —> reads only one line at a time
f.readlines() —> creates a list of strings with each list representing a line in the file

To write data to a file, the write function is used such as f.write(“End of file”) . This prints the line “End of file” to the file.

Reading and writing data to files is usually done by using exceptions in order to prevent the program from crashing when an error is encountered. It is generally good programming practice to use exceptions to catch errors especially when dealing with big programs. The Python syntax for exceptions is

try:
    statements
except <exception name>:
    statements
except <exception name>:
    statements
except <exception name>:
    statements
finally:
    statements

The main success scenario is contained in the try block. This means that every statements that we consider as the main code should be within this block because it will be the first to be executed.
If the try block does not successfully execute, the except block will be executed next sequentially starting with the first one that matches the error generate by the try block.
The finally block will always be executed and it is in this block where you close files.

One common error you will encounter when dealing with files is the IOError which is executed when the file cannot be located. Here is an example


try:
     f = open("theFile.txt", "r")
     data = f.read()
except IOError as one:
     print("\nfailed to open file")
     print(one,"\n")
finally:
     print("finally cleaning up")
    
Read more on excepts here

Here is a simply program to write the a right a bunch of triangles to theFile.txt
The pattern to write to the file are

*
**
***
****
*****
******
*******
********

********
********
********
********
********
********
********
********

********
*******
******
*****
****
***
**
*

The print sequence for the first right angle triangle is

def printT(n):
    for i in range (n):
        print( "*" * (i+1) )

The print sequence for the square is

def printT(n):
    for i in range (n):
        print( "*" * n )

The print sequence for the upside right angle triangle is


def printT(n):
    for i in range (n+1):
        print( "*" * (n-i) )

All that is left it to combine the three printing sequence into one function and enclose in the try block as we print to the file



def printT(n):
    filename = "theFile.txt"
   
    try:
        # Open the file
        f = open(filename, "w")
       
        f.write("output:\n")
       
        for i in range (n):
            f.write( "*" * (i+1) + "\n" )
       
        f.write( "\n" )
       
        for j in range (n):
            f.write( "*" * n + "\n" )
       
        f.write( "\n" )
       
        for k in range (n+1):  
            f.write( "*" * (n-k) + "\n" )
       
    except IOError as one:
        print("\nfailed to open file")
        print(one,"\n")
    finally:
        f.close()
        print("\n" + filename + " closed!")

printT(4)
# Output expected

# printT(4)
# *
# **
# ***
# ****

# ****
# ****
# ****
# ****

# ****
# ***
# **
# *

Share your thoughts