Python Reference ยท Files, Paths and Text I/O
Python file.read(), readline() and readlines()
Reference for reading from a Python file object: read(size), readline(), readlines(), end-of-file behavior, newline handling and memory use.
A file object opened for reading offers three ways to pull data out. read() returns everything (or a chunk of a given size) as one string, readline() returns one line, and readlines() returns all lines as a list.
All three move the file's position forward, so a second call continues where the first stopped. At the end of the file they return an empty value instead of raising an error, which is how you detect "no more data".
with open("data.txt", encoding="utf-8") as f: text = f.read()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
file.read(size=-1) file.readline(size=-1) file.readlines(hint=-1)
| Name | Description |
|---|---|
size (read) |
Maximum number of characters to read in text mode, or bytes in binary mode. -1 or None reads to the end. |
size (readline) |
Maximum characters (or bytes) to read from the current line. A shorter result means the line was cut short. |
hint (readlines) |
Stop after roughly this many characters or bytes have been read, finishing the current line. -1 reads everything. |
Return value: read() returns a str (text mode) or bytes (binary mode). readline() returns one line including its trailing \n. readlines() returns a list of such lines.
Raises: ValueError if the file is closed, io.UnsupportedOperation if the file was not opened for reading, and UnicodeDecodeError in text mode if the bytes do not match the encoding.
Usage notes
- End of file is empty, not an error.
read()andreadline()return""(orb"") at the end. A blank line in the middle of a file is"\n", which is truthy, soif not line:reliably detects the end. read()loads everything into memory. That is fine for small files. For large ones, iterate over the file or read fixed-size chunks.- Lines keep their newline. Use
line.rstrip("\n")orline.strip()when you do not want it. The last line has no\nif the file does not end with one. - Positions advance. After
read(), callingread()again gives"". Useseek(0)to start over. - Text-mode size counts characters, while binary-mode size counts bytes. A multi-byte UTF-8 character is one character in text mode.
readlines()vs. iteration.for line in f:gives the same lines one at a time without building a list; prefer it when you only loop once. See iterating over files.- Mixing methods is fine:
readline()followed byread()continues from the same position. In text mode, though,tell()raisesOSErrorafternext(f)or while looping withfor line in f; usereadline()in a loop if you need positions. - Encoding. Pass
encoding="utf-8"explicitly; see open() modes and encodings.