The Wayback Machine - https://web.archive.org/web/20240623085946/https://www.geeksforgeeks.org/read-file-as-string-in-python/
Open In App

Read File As String in Python

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let’s delve into them one by one.

Read File As String In Python

Below are some of the approaches by which we can read the file as a string in Python:

example.txt

This is the same file data that we will use throughout the article.

Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast

Read File As String Using read() Method

In this example, the file at the specified path (‘example.txt’) is opened, and its entire content is read into a string using the read() method. The with statement ensures proper handling of the file, automatically closing it after reading.

Python3




file_path = 'example.txt'
 
with open(file_path, 'r') as file:
    file_content = file.read()
 
print(file_content)


Output:

Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast

Python Read File As String Using readline() Method

In this example, the file (‘example.txt’) is opened, and its content is read line by line in a loop using the readline() method. Each line is appended to the file_content string, creating a single string containing the entire file content.

Python3




file_path = 'example.txt'
 
with open(file_path, 'r') as file:
    file_content = ''
    line = file.readline()
     
    while line:
        file_content += line
        line = file.readline()
 
print(file_content)


Output:

Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast

Read File As String Using readlines() Method

In this example, the file (‘example.txt’) is opened, and its content is read into a list of strings using the readlines() method. The lines are then joined into a single string using the join() method, creating the complete file content.

Python3




file_path = 'example.txt'
 
with open(file_path, 'r') as file:
    lines = file.readlines()
    file_content = ''.join(lines)
 
print(file_content)


Output:

Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast

Python Read File As String using pathlib Module

In this example, the pathlib module is employed to read the content of the file (‘example.txt’) as a string. The read_text() method is used on a Path object, providing a concise and modern approach to file reading.

Python3




from pathlib import Path
 
file_path = Path('example.txt')
 
file_content = file_path.read_text()
 
print(file_content)


Output:

Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast



Similar Reads

Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 min read
Read a Particular Page from a PDF File in Python
Document processing is one of the most common use cases for the Python programming language. This allows the language to process many files, such as database files, multimedia files and encrypted files, to name a few. This article will teach you how to read a particular page from a PDF (Portable Document Format) file in Python. Method 1: Using Pymu
4 min read
How to read from a file in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line
5 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
Upload file and read its content in cherrypy python
CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time.
3 min read
Read List of Dictionaries from File in Python
A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python. Read a List of Dictionary from Text Files in PythonUsing Pickle ModuleUsing read( ) MethodThe problem s
3 min read
How to read Dictionary from File in Python?
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.literal_eval() method : Function safer than the ev
2 min read
Read Properties File Using jproperties in Python
In this article, we are going to see how to read properties file in python using jproperties module. It is a Java Property file parser and writer for Python. For installation run this command into your terminal. pip install jproperties Various properties of this module: get() Method or Index-Based access to reading the values associated with the ke
2 min read
three90RightbarBannerImg