Essetee's Website


Working with files


With your text editor of choice, make a new file with the name FileHandlers.py and paste the following content.


import os

class FileHandler:
    def __init__(self, filename):
        self.filename = filename

    def exists(self):
        """Check if the file exists."""
        return os.path.exists(self.filename)

    def write_file(self, content):
        """Write content to the file."""
        with open(self.filename, 'w') as file:
            file.write(content)

    def read_file(self):
        """Read content from the file."""
        if not self.exists():
            return "File does not exist."
        with open(self.filename, 'r') as file:
            return file.read()

    def append_file(self, content):
        """Append content to the file."""
        with open(self.filename, 'a') as file:
            file.write(content)

    def delete_file(self):
        """Delete the file."""
        if self.exists():
            os.remove(self.filename)
            return "File deleted successfully."
        else:
            return "File does not exist."
            
            

# Example usage:

from FileHandlers import FileHandler

fh = FileHandler('example.txt') # replace example.txt with your filename

# Check if file exists
print(fh.exists()) # Output: False (assuming the file doesn't exist)

# Write to file
fh.write_file("Hello, World!")

# Read from file
print(fh.read_file()) # Output: Hello, World!

# Append to file
fh.append_file("\n" + Appended content")

# Read again to see the appended content
print(fh.read_file()) # Output: Hello, World!\nAppended content.

# Delete the file
print(fh.delete_file()) # Output: File deleted successfully.

# Try reading from a deleted file (should return error message)
print(fh.read_file()) # Output: File does not exist.