Techniques for Reading Files

As we mentioned at the beginning of the chapter, Python provides several techniques for reading files. You’ll learn about them in this section.

All of these techniques work starting at the current file cursor. That allows us to combine the techniques as we need to.

The Read Technique

Use this technique when you want to read the contents of a file into a single string, or when you want to specify exactly how many characters to read. This technique was introduced in Opening a File; here is the same example:

 with​ open(​'file_example.txt'​, ​'r'​) ​as​ file:
  contents = file.read()
 
 print​(contents)

When called with no arguments, it reads everything from the current file cursor all the way to the end of ...

Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.