In Python, you can read the complete contents of a text file into a string using the read() method. This tutorial shows how to read a file as a string, use a with statement to close the file automatically, specify UTF-8 encoding, handle missing files, and remove or preserve newline characters when needed.
Read a text file into a string in Python
To read an entire text file into one Python string, open the file in text read mode and call read() on the file object. The returned value is a str containing the file’s text, including newline characters that are present in the file.
with open(file_path, "r", encoding="utf-8") as file:
data = file.read()
The with statement is generally the most convenient form because Python closes the file automatically when the block finishes, including when an exception occurs while processing the file.
Steps to read the whole file as one string
- Open the text file in read mode using
open(). - Call
read()on the file object. - Store the returned text in a string variable.
- Close the file, or use a
withstatement so that it is closed automatically.
The default mode of open() is "r", which means text read mode. Therefore, open("data.txt") can read a text file without explicitly supplying "r". Specifying the mode can still make the intent of the code clearer.
1. Read file as a string
In this example, we assume that a file with two lines of text is present at D:/data.txt. The program opens the file, calls read() to get all of its contents as a string, closes the file, and prints the string.
Python Program
#open text file in read mode
text_file = open("D:/data.txt", "r")
#read whole file to a string
data = text_file.read()
#close file
text_file.close()
print(data)
Output
Hello World!
Welcome to www.tutorialkart.com.
The variable data is a single Python string. The line break between the two lines is part of that string because read() preserves newline characters from the text file.
2. Negative scenario – File path incorrect while reading the file
In this example, we assume that we are trying to read content of a file that is not present. In other words, file path is incorrect.
Python Program
#open text file in read mode
text_file = open("D:/data123.txt", "r")
#read whole file to a string
data = text_file.read()
#close file
text_file.close()
print(data)
Output
Traceback (most recent call last):
File "d:/workspace/fipics/rough.py", line 2, in <module>
text_file = open("D:/data123.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'D:/data123.txt'
Python raises FileNotFoundError because no file exists at the path supplied to open(). Check the directory, filename, and file extension when you see this exception.
3. Check if file is present before reading file to a string
In this example, the program checks whether the path refers to an existing file before trying to read it. If the file is present, its contents are read into a string.
To check if a file is present, we use os.path.isfile() function.
Python Program
import os
file_path = "D:/data123.txt"
#check if file is present
if os.path.isfile(file_path):
#open text file in read mode
text_file = open(file_path, "r")
#read whole file to a string
data = text_file.read()
#close file
text_file.close()
print(data)
If the file exists, the program reads and prints its contents. If it does not exist, the body of the if statement is skipped, so this particular program does not attempt to open the missing file.
Read a file as a string using with open()
Instead of calling close() manually, use a context manager with with open(...). The file remains open inside the indented block and is automatically closed when execution leaves that block.
file_path = "D:/data.txt"
with open(file_path, "r") as text_file:
data = text_file.read()
print(data)
Output
Hello World!
Welcome to www.tutorialkart.com.
The value in data remains available after the with block has ended even though the file itself has been closed.
Read a UTF-8 text file into a Python string
Text files are decoded into Python strings. When you know the file’s encoding, specify it explicitly with the encoding argument. UTF-8 is a common encoding for text files and supports a wide range of characters.
with open("data.txt", "r", encoding="utf-8") as text_file:
data = text_file.read()
print(data)
Using an explicit encoding also makes the expected file format clear and avoids relying on the platform’s default text encoding.
Read a file into a string and remove surrounding newlines
The read() method preserves newline characters. If you only want to remove whitespace and newline characters from the beginning and end of the file content, call strip() on the returned string.
with open("data.txt", "r", encoding="utf-8") as text_file:
data = text_file.read().strip()
print(data)
strip() does not remove newline characters that occur between lines. It removes whitespace only from the two ends of the complete string.
Read a text file as one string without line breaks
If the requirement is to combine all lines into one line, read the lines and join them explicitly. The separator you choose determines what appears between the original lines.
with open("data.txt", "r", encoding="utf-8") as text_file:
data = " ".join(line.strip() for line in text_file)
print(data)
Output
Hello World! Welcome to www.tutorialkart.com.
Here, strip() removes the newline from each line and " ".join(...) places a space between the resulting strings. This is different from simply calling read(), which retains the line breaks.
Read only one line from a text file as a string
If you need only one line rather than the entire file, use readline(). It returns the next line as a string.
with open("data.txt", "r", encoding="utf-8") as text_file:
first_line = text_file.readline()
print(first_line)
Unless it is the final line without a line terminator, the returned string can include a trailing newline character. Use rstrip("\r\n") if you specifically want to remove the line-ending characters.
with open("data.txt", "r", encoding="utf-8") as text_file:
first_line = text_file.readline().rstrip("\r\n")
print(first_line)
Read a file line by line instead of one large string
read() loads the requested file content into a string. If you do not need the whole file at once, you can iterate over the file object and process one line at a time.
with open("data.txt", "r", encoding="utf-8") as text_file:
for line in text_file:
print(line.rstrip("\r\n"))
This form is useful when each line can be processed independently and you do not require one string containing the entire file.
Read text file lines into a Python list
If you need a separate string for every line, you can build a list while iterating through the file.
with open("data.txt", "r", encoding="utf-8") as text_file:
lines = [line.rstrip("\r\n") for line in text_file]
print(lines)
Output
['Hello World!', 'Welcome to www.tutorialkart.com.']
This produces a list of strings rather than one string containing the complete file.
Handle FileNotFoundError when reading a file as a string
Another way to deal with a possibly missing file is to attempt the read operation and catch FileNotFoundError. This is useful when your program needs to provide an alternate action or message if the file cannot be found.
file_path = "D:/data123.txt"
try:
with open(file_path, "r", encoding="utf-8") as text_file:
data = text_file.read()
print(data)
except FileNotFoundError:
print("File not found:", file_path)
Output when the file does not exist
File not found: D:/data123.txt
Read a file as a string using pathlib.Path
Python’s pathlib module also provides Path.read_text(), which reads the contents of a text file and returns them as a string.
from pathlib import Path
file_path = Path("data.txt")
data = file_path.read_text(encoding="utf-8")
print(data)
This is a compact option when you already represent filesystem paths with Path objects. Like read(), read_text() returns the file content as a Python string.
Choosing how to read text from a Python file
| Requirement | Python approach |
|---|---|
| Read the entire text file as one string | file.read() |
| Automatically close the file after reading | with open(...) |
| Read a UTF-8 text file | open(..., encoding="utf-8") |
| Read only the next line | file.readline() |
| Process a file one line at a time | Iterate over the file object |
| Store individual lines in a list | Iterate and build a list |
| Read text through a Path object | Path.read_text() |
| Remove whitespace at the beginning and end | file.read().strip() |
Python file-to-string summary
Use read() when you need the complete contents of a text file as one string. A with open(...) block handles closing the file automatically, and specifying encoding="utf-8" makes the expected text encoding explicit. Use readline() or line-by-line iteration when your program does not need the whole file at once.
In this Python Tutorial, we learned how to read file content to a string.
TutorialKart.com