Read the file as a string in Python [5 Methods]

In this Python tutorial, I will explain How to read the file as a string in Python using different methods with illustrative examples.

Python is one of the most popular programming languages for working with data, automating tasks, web development, and various other applications. One of the most fundamental operations when working with data is reading from files.

Methods to read the file as a string in Python

There are five different ways to read the file as a string in Python

  • The read() method
  • The readline() method
  • The readlines() method
  • The list comprehension
  • Exception handling

Let’s see them one by one using demonstrative examples:

Method 1: Python read file into string using the open() function with read() method

The built-in open() function allows us to open a file in various modes in Python. When combined with the read() method, it enables us to read the entire content of a file into a single string in Python

Scenario: We have a text file containing a list of US presidents, and we want to read all of its content at once through Python.

Case 1: The read() method without any argument reads, the entire file and returns it as a single string.

with open('usa_presidents.txt', 'r') as file:
    content = file.read()
print(content)
withUsing with to open files is a best practice in Python because it ensures that the file is properly closed after its suite finishes
open()To open a file in various modes in Python.
‘r’It stands for “read mode”. It means that we’re opening the file to read its contents in Python.
as fileThis is part of the with statement, and it assigns the opened file to the variable named file.
read()The read() method reads the entire contents of the opened file into a string(if no argument have been passed.
The explanation of the above Python code.

Output: The entire content of the text file usa_presidents.txt is printed in Python.

George Washington
John Adams
Thomas Jefferson
Text file in Python with USA_presidents names
The “usa_presidents” text file in Python
python read file into string
Python code with Output

Case 2: The read() method with arguments, reads a specified number of characters from the file.

In the same scenario,

with open('usa_presidents.txt', 'r') as file:
    content = file.read(15)
print(content)

Output: Here, the read() function can only read 15 characters from the file in Python.

George Washingt
Read the file as a string in Python

This way, we can use the read() function to read Python text files into strings.

Method 2: How to read File as String in Python using the readline() Method

The readline() method in Python reads one line at a time from the file in Python. If called again, it reads the next line, and so on.

Scenario: Imagine we have a tourist brochure detailing landmarks in the USA, and we want a preview by reading the first two landmarks listed. The readline() lets us peek at the first two lines of the text file one by one in Python.

with open('usa_landmarks.txt', 'r') as file:
    first_landmark = file.readline().strip()
    second_landmark = file.readline().strip()
print(first_landmark)
print(second_landmark)

Output: In our example, “Statue of Liberty” is the first line, and “Mount Rushmore” is the second line in usa_landmarks.txt, so that’s the output. The strip() function in Python is used to remove any leading or trailing whitespace, including the newline character.

Statue of Liberty
Mount Rushmore
Python text file
Python text file “usa_landmarks.txt”
How to read File as String in Python
Python code with Output

Note: If we pass the argument in the readline() then, only that many characters will be printed. and in case the passed argument is bigger than the number of characters in the first line of the file in Python then only the first line will be printed.

This way, we can use the readline() method in Python, and read the file into string variables.

Method 3: Read File as String in Python using the readlines() function

While read() reads the whole text file into a single Python string, and readline() reads a line at a time, readlines() reads the text file line by line and returns a list of strings in Python.

Scenario: We possess a list of state capitals in a file in Python. We wish to read the file line by line and store each line as an individual string inside a Python list. The readlines() reads the entire file and returns a list of strings.

with open('usa_capitals.txt', 'r') as file:
    lines = file.readlines()
    print('The list of the strings:',lines)
content = ''.join(lines)
print('After join:', content)

Output: The readlines() method reads the file and returns a Python list of strings, where each string is a line from the text file. The join method is then used to concatenate these strings into a single string, which is then printed.

The list of the strings: ['California: Sacramento\n', 'Texas: Austin\n', 'Florida: Tallahassee']
After join: California: Sacramento
Texas: Austin
Florida: Tallahassee
File in Python
The text file ‘usa_capitals.txt’
Read File as String in Python
Python code with output

Method 4: Read a text file into a string variable in Python using list comprehension

We can also use list comprehension in Python to read specific lines or apply transformations while reading from a text file.

Scenario: We have a file listing US cities, but we’re only interested in cities with “San” in their name. List comprehension in Python allows us to filter and retrieve only the desired lines.

with open('usa_cities.txt', 'r') as file:
    content = ''.join([line for line in file if "San" in line])
print(content)

Output: The list comprehension in Python iterates through each line in the txt file and filters out only the lines that contain the substring “San”. In this case, only “San Francisco” matches the condition, so it is the only line printed.

San Francisco
Python txt file
Python txt file “usa_cities”
How to read a text file in Python string variable
Python code with output

This way, we can read the txt file into string variables in Python with a filter using list comprehension.

Method 5: How to read files into a string in Python with exception handling

Exception handling is crucial to ensure our code doesn’t crash when encountering unexpected file errors, like missing files or permission issues in Python.

Scenario: While accessing a list of US national parks from a file, there’s a chance the file might be missing or access could be restricted. Exception handling in Python ensures our code gracefully manages such unexpected situations, providing informative messages instead of crashing.

try:
    with open('usa_national_parks.txt', 'r') as file:
        content = file.read()
    print(content)
except FileNotFoundError:
    print("The file was not found!")
except PermissionError:
    print("Permission denied while trying to read the file.")
except Exception as e:
    print(f"An error occurred: {e}")

Output: In this example, the file usa_national_parks.txt is read without any errors, so the content of the file is printed directly.

Yellowstone
Yosemite
Grand Canyon
Text file in Python
‘usa_national_parks.txt’ Text file in Python
Python read file into string variable
Python code with output

If the file were missing, the FileNotFoundError error in Python would be triggered, and “The file was not found!” would be printed. If there was a permission issue accessing the file in Python, “Permission denied while trying to read the file.” would be printed. The final Python except block would catch any other unforeseen errors that might occur.

Conclusion

This article explains how to Read the file as a string in Python using five different methods such as read(), readline(), readlines(), list comprehension, and exception handling with illustrative examples. Each method tailors to different situations, ensuring that reading from files is efficient, safe, and convenient.

Knowing, how to read the file as a string in Python can be a routine task, made effortless by the language’s built-in capabilities.

You may also like to read: