How To Read Text File Into String Variable In Python?

Python provides different ways to read a text file and put the text file content into a string variable. In this tutorial, we will learn how to read a text file into the string variable in Python.

Read Text File Into String Variable

The file read() method can be used to read the whole text file and return as a single string. The read text can be stored into a variable which will be a string.

f = open("mytextfile.txt")

text = f.read()

f.close()

print(text)

Alternatively the file content can be read into the string variable by using the with statement which do not requires to close file explicitly.

with open("mytextfile.txt") as f:
   text = f.read()

print(text)

Read Text File Into String Variable with Path Module

The Path module provides the ability to read a text file by using the read_text() method. The file name is provided the Path() method and after opening the file the read_text() method is called.

from pathlib import Path

text = Path("mytextfile.txt").read_text()

print(text)

Read Text File Into String Variable By Removing New Lines “\n”

Regular text files contains multiple lines the end of line exist in every line which is “\n” in Linux. The string types provides the replace() method in order to replace specified characters with other characters. After reading the text file the replace() method can be called to replace the new line or end of line with noting.

f = open("mytextfile.txt")

text = f.read().replace("\n","")

f.close()

print(text)

Leave a Comment