File I/O

Files are a common way of managing data. You are used to using files to hold documents, such as Word files, pdf files, or jpg files, for a few examples. These files have complicated formats to encode the formatting directives or image data. The files that we will work with will be much simpler. They will contain only text. In this chapter, you will learn how to read the data from these text files so your program can manipulate them, and also how to write data that your program computes to a text file for later use.

We often refer to reading from files and writing to files as File I/O, which is short for File Input/Output. Reading from files is inputting data to our programs, while writing data to files is output.

In order to work with a file, we first need to “open” the file by calling the open function. When we open the file, we provide the name of the file to read from, and also whether we will read from the file or write to the file. Here is an example where we open a file called myfile.txt, which we will read from:

open( "myfile.txt", 'r')

The open function returns a file object. 

Reading from a file

Often when we read from a file, we will read one line at a time and do something with that line. To accomplish that, we use a new kind of statement, a with statement, and then use a for loop within the with statement to get each line, like this:

with open( "myfile.txt", 'r') as reader:

    for line in reader:

        print (line)

The statement show above will read each line of a file and display it to the user.

Writing to a file

To write text to a file, we again need to open the file. This time, we will pass ‘w’ as the second parameter to indicate that we plan to write to the file. We use the with statement again to open the file and put the code that we want to write to the file inside the with statement. To write a value to the file, we will call file’s write function, like this:

with open( "myfile.txt", 'w') as writer:

    writer.write ("Hello, world!")

When we use ‘w’ as the second parameter to the open function, the file will be overwritten if it already exists. If what we want to do instead is to append to the end of the file, we use ‘a’ instead of ‘w’.

File errors

A lot of errors can arise when we are working with files. The most common of these occurs when we try to read from a file that does not exist. In that case, Python will report FileNotFoundError. If you see that, double-check that you have typed the name of the file correctly and that you are running your program in the same folder where the file is.