.read()
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.
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:
All contributors
- BrandonDusch
- Anonymous contributor
- christian.dinh
- Anonymous contributor
- Anonymous contributor
- net1372284738
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours