File I/O

Introduction to file handling

To read or write a file, you must do three things:

  1. Open the file
  2. Use the file (reading or writing)
  3. Close the file

Opening files in Python

The file = open(file_name, mode) command opens and returns (in the variable file) a reference to the named file. In this case, mode would be one of the following:

  • r to read the file (This is the default if mode is omitted).
  • w to erase and write the file.
  • a to append to the end of an existing file.
  • r+ to both read and write.
  • rb, wb, ab, and rb+ to do binary input/output.

An example of this can be:

file = open(file_name) # mode omitted (r used by default) so file is being read     
file = open(file_name,'w') # w used here so writing to file

File methods in Python

The following are some of the methods that come along with the file object in Python:

  • file.read() will read in and return the entire file as a single string, including any newline characters.
  • file.readline() reads and returns a line of text, including the terminating newline (if any). If the empty string is returned, the end of the file has been reached.
  • file.readlines() reads the entire file and returns it as a list of strings, including terminating newlines.
  • file.write(string) writes the string to the file, and it returns the number of characters written.

An alternative of using the read, readline and readlines methods can be iterating over them using a loop. For example:

for line in file:
  statements

The above code will read each line in the file, assign it to the variable line, and execute the statements. Here, the statements are indented as usual.

Closing files in Python

Closing the file is a mandatory step as leaving the file open when you are done with it is likely to cause problems. The file.close() command is used for closing the file.

An example of this can be:

file = open(file_name) # file being read
file.close() # closing the file

An excellent alternative to closing files in Python is using the with operator.

with open(file_name) as file: 
  statements

The above code will open the file, execute the statements once, and automatically close the file without explicitly using the close method.

Note: Since the statements are executed only once, they typically consist of a loop to read and process each line in turn. Indentation is as usual, meaning the statements are indented under the with line.

Files example

The following is an example of reading a text file, printing its contents, and closing the file:

Get hands-on with 1200+ tech skills courses.