I/O

One of the major features of a modern computer is the ability to store and retrieve data from the computer’s file system. So, we need to be able to access the file system in our code in order to build useful programs. Thankfully, most modern programming languages include a way to do this.

I/O in Flowcharts & Pseudocode

Most operations working with files in code take the form of method calls. So, we will primarily use the call block to represent operations on files:

Operation Flowchart Pseudocode
Open File Open File Flowchart Block Open File Flowchart Block
S = “file.txt”
FILE = open(S)
Read from File Read from File Flowchart Block Read from File Flowchart Block
S = FILE.read()
Write to File Write to File Flowchart Blocks Write to File Flowchart Blocks
FILE.write(X)

I/O in Python

Let’s review the syntax for working with files in Python.

Reading Files

To open a file in Python, we can simply use the open() method. Here is an example:

import sys

try:
    reader = open(sys.argv[1])
except FileNotFoundError as e:
    print("FileNotFoundError: {}".format(e))
    sys.exit()
except IndexError as e:
    print("IndexError: {}".format(e))
    reader = sys.stdin
  
with reader:
    # -=-=-=-=- MORE CODE GOES HERE -=-=-=-=-

In this example, the program will try to open a file provided as the first command-line argument. If no argument is provided, it will automatically read from standard input instead. However, if an argument is provided, it will try to open it as a file. In addition, we can use a With statement to make sure the file is properly closed once it is open.

Once we have opened the file, we can read the file just like we would any other input:

for line in reader:
    line = line.strip()
    if not line or len(line) == 0:
        break
    # use line variable

Writing Files

To write to a file, we must open it a different way. In Python, we must provide an optional "w" argument to the open() method call to make the file writable:

import sys

try:
    with open(sys.argv[1], "w") as writer:
        writer.write("Hello World")
        writer.write("\n")

except IndexError as e:
    # no arguments provided
    print("IndexError: {}".format(e))
    sys.exit()
except IOError as e:
    # unable to write to the file
    print("IOError: {}".format(e))
    sys.exit()
except Exception as e:
    # unknown exception
    print("Exception: {}".format(e))
    sys.exit()

This example shows to how to open a file for writing using the open() method inside of a With statement. It also lists several of the common exceptions and their cause.

Resources