Python Read Files

Last updated: May 25, 2026

`read()` Method

The read() method reads a string from an open file. It is important to note that Python strings can have binary data apart from text data.

Syntax:

fileobject.read([count])

Here, the passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.

Example:

# creates a new file sample.txt give write permissions on file
f = open('sample.txt', 'w')

# writing content into file using write method
f.writelines(['python is easy\n', 'python is portable\n', 'python is comfortable'])
f.close()

f = open('sample.txt', 'r')

# reading first 21 bytes from the file using read() method
print(f.read(21))

Output:

python is easy
python

`readline()` Method

Python file method readline() reads one entire line from the file. A trailing newline character is kept in the string. If the size argument is present and non-negative, it is a maximum byte count including the trailing newline and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.

Syntax:

fileobject.readline(size)

The size parameter is the number of bytes to be read from the file. The return value is the line read from the file.

Example:

# writing content into file using write method
f = open('sample.txt', 'w')

# writing content into file using write method
f.writelines(['python is easy\n', 'python is portable\n', 'python is comfortable'])
f.close()

f = open('sample.txt', 'r')

# reading first line of the file using readline() method
print(f.readline())
print(f.readline(10))

Output:

python is easy
python is

`readlines()` Method

Python file method readlines() reads until EOF using readline() and returns a list containing the lines. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. An empty string is returned only when EOF is encountered immediately.

Syntax:

fileobject.readlines(sizehint)

The sizehint parameter is the number of bytes to be read from the file. The return value is a list containing the lines.

Example:

# creates a new file sample.txt give write permissions on file
f = open('sample.txt', 'w')

# writing content into file using write method
f.writelines(['python is easy\n', 'python is portable\n', 'python is comfortable'])
f.close()

f = open('sample.txt', 'r')

# reading all the line of the file using readlines() method
print(f.readlines())
print(f.readlines(15))

Output:

['python is easy\n', 'python is portable\n', 'python is comfortable']
['python is easy\n', 'python is portable\n']