![]() |
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 PythonBelow 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, Read File As String Using read() MethodIn 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
Output: Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast
Python Read File As String Using readline() MethodIn 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
Output: Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast
Read File As String Using readlines() MethodIn 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
Output: Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast
Python Read File As String using pathlib ModuleIn 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
Output: Hii,
I am a GeeksforGeeks student.
I am a web developer and DSA enthusiast
|
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |