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:
|Read from File||
|Write to File||
I/O in Python
Let’s review the syntax for working with files in Python.
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:
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.