.read()

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:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Python on Codecademy