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

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:

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:

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:

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.