Reading from a file

Let's create a simple text file, read_file.txt with the following text: I am learning Python Programming using the Raspberry Pi Zero and save it to the code samples directory (or any location of your choice).

To read from a file, we need to make use of the Python's in-built function: open to open the file. Let's take a quick look at a code snippet that demonstrates opening a text file to read its content and print it to the screen:

if __name__ == "__main__":
# open text file to read
file = open('read_line.txt', 'r')
# read from file and store it to data
data = file.read()
print(data)
file.close()

Let's discuss this code snippet in detail:

  1. The first step in reading the contents of the text file is opening the file using the in-built function open. The file in question needs to be passed as an argument along with a flag r that indicates we are opening the file to read the contents (We will discuss other flag options as we discuss each reading/writing files.)
  2. Upon opening the file, the open function returns a pointer (address to the file object) that is stored in the file variable.
       file = open('read_line.txt', 'r')
  1. This file pointer is used to read the contents of the file and print it to the screen:
       data = file.read() 
print(data)
  1. After reading the contents of the file, the file is closed by calling the close() function.

Run the preceding code snippet (available for download along with this chapter—read_from_file.py) using IDLE3 or the command-line terminal. The contents of the text file would be printed to the screen as follows:

    I am learning Python Programming using the Raspberry Pi Zero