Read File As String in Python
Last Updated :
01 Feb, 2024
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
Share your thoughts in the comments
Please Login to comment...