Python implementing a class supporting text file read and write
We will create a class named TextFileHandler class, which will support reading and writing text files. This class will contain two main methods:read_file for reading file content,write_file for writing content to a file.
Example
class
TextFileHandler:
def
init
(
self
,
filename
)
:
self
.
filename
=
filename
def
read_file
(
self
)
:
try
:
with
open
(
self
.
filename
,
'r'
)
as
file
:
content
=
file
.
read
(
)
return
content
except
FileNotFoundError:
return
"File not found."
def
write_file
(
self
,
content
)
:
with
open
(
self
.
filename
,
'w'
)
as
file
:
file
.
write
(
content
)
return
"File written successfully."
Example usage
handler
=
TextFileHandler
(
'example.txt'
)
handler.
write_file
(
"Hello, World!"
)
(
handler.
read_file
(
)
)
Code analysis:
__init__Method: this is the class constructor, used to initialize an instance of the class. It accepts a file name as a parameter and stores it in the instance variableself.filenameit.read_fileMethod: this method is used to read file content. It useswith openstatement to open the file in read mode and read its content. If the file does not exist, it catchesFileNotFoundErrorexception and returns "File not found.".write_fileMethod: this method is used to write content to a file. It useswith openstatement to open the file in write mode and write the passed content to the file. After successful writing, it returns "File written successfully.".
Output result:
Hello, World!
Python3 Examples