Python Glossary Русский

all Python 3Files & I/Ofunction

io.TextIOBase.read()

reading

Read the whole file into a single string, or at most size characters if given; on a large file this loads everything into memory — iterate by lines instead.

Syntax

f.read(size=-1)

The cursor does not rewind: after f.read() the file is exhausted, so a second call inside the same with block returns an empty string — the usual cause of "my file suddenly reads as empty". Call f.seek(0) to read it again. The size argument counts characters in text mode but bytes in binary mode, and for non-ASCII data those are not the same thing.

Examples

with open('demo.txt', 'w') as f:
    f.write('line1\nline2\nline3\n')
with open('demo.txt') as f:
    content = f.read()
print(repr(content))  # → 'line1\nline2\nline3\n'
with open('demo.txt') as f:
    print(f.read(5))  # → line1 (ровно 5 символов)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy