HOWTO · Python
How to Read File to a String in Python
Learn how to read a text file into a Python string with open() and read() or Path.read_text(), choose an encoding, handle line endings, and process large files without loading them all at once.
On this page
To read a text file into one Python string, open it in text mode and call read(). Choose an encoding that matches the file, and remember that assembling the whole contents requires memory proportional to the file’s decoded text. For large inputs, iterate over lines when you can process them one at a time.
Read a text file into a string with open() and read()
Use a context manager to open a text file, read all its contents, and close it when the block ends. This self-contained example creates a UTF-8 file before reading it:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "example.txt"
path.write_text("First line.\nSecond line.\n", encoding="utf-8")
with path.open("r", encoding="utf-8") as file:
content = file.read()
print(content, end="")
First line.
Second line.
read() returns the remaining text as one string; called on a newly opened file, that is the full file. The with block closes the file even if the block exits due to an error. The example uses a temporary file, so it needs no separately supplied fixture. It prints the file contents exactly as written:
Set an encoding when opening a text file
Text files store bytes, which Python decodes into characters. Pass encoding when opening a file if you know its encoding; UTF-8 is common, but it is not correct for every file. A wrong choice can produce garbled text or a decoding error. This example writes and reads UTF-8 data using the same encoding:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "message.txt"
path.write_text("café", encoding="utf-8")
with path.open("r", encoding="utf-8") as file:
content = file.read()
print(content)
If a file’s encoding is unknown, identify it from its producer or documentation rather than assuming that a particular encoding will work. encoding belongs to the text decoding step; it is not used when a file is opened in binary mode.
Read a file with Path.read_text()
Path.read_text() is a concise alternative when you have a path and want the complete file as a string. It opens, reads, and closes the file for you. Specify an encoding explicitly when the file’s encoding is known:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("One note.", encoding="utf-8")
content = path.read_text(encoding="utf-8")
print(content)
Like open() with read(), this reads the whole file into memory. In current Python, omitting encoding uses the default text encoding, which can depend on the environment; passing the known encoding makes the choice explicit.
Combine lines with readlines() or iteration
Use readlines() if you need a list to inspect or transform individual lines before combining them. It reads all lines into memory, and each returned line normally retains its line ending. Calling "".join(lines) concatenates them without adding separators, so those existing endings remain. Use a separator such as " " only when you deliberately want to replace line boundaries with spaces.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "lines.txt"
path.write_text("red\nblue\n", encoding="utf-8")
with path.open("r", encoding="utf-8") as file:
lines = file.readlines()
content = "".join(lines)
print(content, end="")
For a large file that can be handled one line at a time, iterate over the open file instead of building a list:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "lines.txt"
path.write_text("red\nblue\n", encoding="utf-8")
with path.open("r", encoding="utf-8") as file:
for line in file:
print(line, end="")
Iteration avoids keeping every line in a list. If you later join all processed lines into one final string, that result still needs memory proportional to its size.
Handle newlines, file size, and binary data
In the default text mode, universal newline handling translates \r\n and \r line endings to \n as text is read. The resulting string still contains line breaks; read() does not remove them. Use splitlines() when you want lines without their line-ending markers, or strip a known line ending from each line. Avoid assuming rstrip() removes only a newline: with no argument it removes all trailing whitespace.
Reading a whole file into a string needs memory for the decoded contents, and intermediate lists or copies can increase peak memory use. For large files, process each line and discard it before reading the next when the task allows. If the task requires one final string, the string itself must fit in memory.
Binary files should be opened with "rb"; read() then returns bytes, not a decoded string. Keep the data as bytes for binary processing, or decode it with the correct encoding when it represents text. No single text-reading method is right for every file: use open() with read() or Path.read_text() for a complete string, and line iteration when streaming is more important than assembling one.