Create a class FileManager that handles private file paths. Include methods to read, write, and modify files while ensuring that invalid file paths are handled gracefully.
Example 1:
Input: "/path/to/valid/file" Output: "File content"
Example 2:
Input: "/path/to/invalid/file" Output: "File not found"
You can use exception handling to catch and handle file not found errors.
class FileManager:
def __init__(self, file_path):
self._file_path = file_path
def read_file(self):
try:
with open(self._file_path, 'r') as file:
return file.read()
except FileNotFoundError:
return "File not found"
def write_file(self, content):
try:
with open(self._file_path, 'w') as file:
file.write(content)
except FileNotFoundError:
return "File not found"
# Test the class
# Replace with valid and invalid paths for testing
file_manager = FileManager("/path/to/valid/file")
print(file_manager.read_file()) # Output: File content
file_manager = FileManager("/path/to/invalid/file")
print(file_manager.read_file()) # Output: File not found
Unlock AI & Data Science treasures. Log in!