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.

</>
Copy
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

  1. Open the text file in read mode using open().
  2. Call read() on the file object.
  3. Store the returned text in a string variable.
  4. Close the file, or use a with statement 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

</>
Copy
#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

</>
Copy
#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

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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

RequirementPython approach
Read the entire text file as one stringfile.read()
Automatically close the file after readingwith open(...)
Read a UTF-8 text fileopen(..., encoding="utf-8")
Read only the next linefile.readline()
Process a file one line at a timeIterate over the file object
Store individual lines in a listIterate and build a list
Read text through a Path objectPath.read_text()
Remove whitespace at the beginning and endfile.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.