Python .read()

Anonymous contributor's avatar
Anonymous contributor
Published May 10, 2021Updated Aug 11, 2023
Contribute to Docs

The .read() file method allows the user to read the contents of an open file and return the number of associated bytes.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

file.read(size)

The size argument is optional and specifies the number of characters (or bytes) to read. The default size is -1, which means the whole file will be read.

Example

The following example reads the full contents of the lorem_ipsum.txt file:

f = open("lorem_ipsum.txt", "w")
f.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.")
f.close()
f = open("lorem_ipsum.txt", "r", encoding='utf8')
read_data = f.read()
print(read_data)
f.close()

This will print the following:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Codebyte Example

The example below reads the first 100 characters of the gullivers_travels.txt file:

Code
Output

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours