Read n bytes

The seek function enables moving the pointer to a specific position and reading a byte or n bytes from that position. Let's re-visit reading write_file.txt and try to read the word excited in the sentence I am excited to learn Python using Raspberry Pi Zero.

if __name__ == "__main__": 
# open text file to read and write
file = open('write_file.txt', 'r')

# set the pointer to the desired position
file.seek(5)
data = file.read(1)
print(data)

# rewind the pointer
file.seek(5)
data = file.read(7)
print(data)
file.close()

The preceding code can be explained in the following steps:

  1. In the first step, the file is opened using the read flag and the file pointer is set to the fifth byte (using seek)—the position of the letter e in the contents of the text file.
  2. Now, we read one byte from the file by passing it as an argument to the read function. When an integer is passed as an argument, the read function returns the corresponding number of bytes from the file. When no argument is passed, it reads the entire file. The read function returns an empty string if the file is empty:
       file.seek(5) 
data = file.read(1)
print(data)
  1. In the second part, we try to read the word excited from the text file. We rewind the position of the pointer back to the fifth byte. Then we read seven bytes from the file (length of the word excited).
  2. When the code snippet is executed (available for download along with this chapter as seek_to_read.py), the program should print the letter e and the word excited:
       file.seek(5) 
data = file.read(7)
print(data)