Skip to content
File Methods

read()

Read at most size characters or bytes from the file.

file.read(size=-1)

file.read() reads and returns up to size characters (or bytes in binary mode) from the current file stream position.

If size is negative or omitted, it reads the entire remaining content of the file.

Parameters

NameDescription
sizeOptional maximum number of characters/bytes to read. Defaults to -1 (entire file).

Returns

A string (or bytes) containing the read data. Returns an empty string/bytes at EOF.

Try it

Run it and change it
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as f:
    f.write('Python 3.14 Guide')
    f.seek(0)
    chunk = f.read(6)
    rest = f.read()
    print(f'Chunk: {chunk}, Rest: {rest}')

Worth knowing

  • Memory efficiency: Reading very large multi-gigabyte files with f.read() loads everything into RAM. Read in chunks (e.g. f.read(4096)) or iterate line-by-line.

Related entries