Python implement a class that supports reading and writing text files
We will create a class namedTextFileHandlerThis class will support reading and writing text files. This class will contain two main methods:read_fileused to read file content,write_fileused to write 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!")
print(handler.read_file())
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!")
print(handler.read_file())
Code explanation:
__init__Method: This is the constructor of the class, used to initialize an instance of the class. It accepts a file name as a parameter and stores it in the instance variableself.filename.read_fileMethod: This method reads file content. It useswith openstatement to open the file in read-only mode and read the file content. If the file does not exist, it catches theFileNotFoundErrorexception 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 writing successfully, it returns "File written successfully.".
Output:
Hello, World!Other extensions
Python3 Examples