Login Sign Up
Challenges / python file read write open close pathlib 2024

python file read write open close pathlib 2024 Challenge

Read the problem description and solve the challenge in the workspace.

Open Full Sandbox Studio
Problem Description

Coding Challenge: Secure Server Log Processor

Difficulty Level

Intermediate

Problem Description

Imagine you're maintaining a highly resilient backend server system. Your task is to build a professional-grade diagnostic function that safely opens and reads server log files.

Instead about writing a basic script that might crash or leak memory, you must build a robust architecture using modern file manipulation techniques. You'll just need to implement a 4-step exception handling structure (try except, else, finally), use object-oriented paths validate developer inputs, and guarantee that system resources are always released;

you must write a function that: 1. Uses object-oriented methods to check if a file exists before trying to open it (avoiding exceptions for normal flow control). 2. Validates that the developer passed valid log file extension (e.g., .txt or .log) to catch development mistakes early. 3, and attempts to read the file separating a "dangerous" file-opening logic from the "safe" data processing logic. 4; raises a custom exception if the file is completely empty (simulating corrupted log data). 5. Always safely closes the file object to prevent memory leaks, regardless of whether a process succeeded, failed, or panicked.

Input & Output Specifications
  • Input:
  • file_path (string or pathlib.Path object): path for a server's log file.
  • Output:
  • Returns the file's content as the string (or None if file doesn't exist or an error occurs).
  • Must print specific messages for the console:
  • When a file doesn't exist (handled via standard flow control, not exceptions).
  • When a custom corrupted file error occurs.
  • When the file processing is really successful (only if no exceptions were raised).
  • When a file is simply securely closed and system resources are basically cleaned up (must happen every time).
Starter Code Boilerplate
from pathlib import Path

# 1. Define your custom exception
class CorruptedLogError(Exception):
    """Raised when the log file is empty or corrupted."""
    pass

def process_server_logs(file_path):
    # Convert input to a Path object
    path = Path(file_path)

    # 2. Use an assertion to catch developer mistakes (ensure .txt or .log extension)
    # YOUR CODE HERE

    # 3. Check if the file exists without using exceptions
    # YOUR CODE HERE

    file_obj = None
    try:
        # 4. Open the file and read it ("dangerous" code)
        pass # YOUR CODE HERE

        # 5. Check if it's empty, if so, raise CorruptedLogError
        pass # YOUR CODE HERE

    except CorruptedLogError as e:
        # 6. Handle the custom exception
        pass # YOUR CODE HERE

    except Exception as e:
        # 7. Handle other unexpected errors
        pass # YOUR CODE HERE

    else:
        # 8. Process success ("safe" code)
        pass # YOUR CODE HERE

    finally:
        # 9. Clean up and close the file, checking the .closed attribute
        pass # YOUR CODE HERE

Hints
  • Modern Paths: Use pathlib and its built-in .exists() method to check for the file's presence, and do not use a try...except block just to check if the file is there; save exceptions for truly unexpected events.
  • ** assert keyword:** Use assert path.suffix in ['.txt', '.log'] to actively crash the program if a developer mistakenly passes the .jpg or .exe file; assertions are strictly for catching bugs during development!
  • Custom Exceptions: Using the generic ValueError for an empty log file is confusing; raising your custom CorruptedLogError makes your code self-documenting.
  • A else clause: Don't stuff too much code into your try block. Put dangerous open() and read() logic inside a try block, but put your success messages or data returning inside the else block.
  • The finally clause: This is your safety net towards prevent memory leaks. Whether the code succeeds fails, or panics finally block runs. Use it to call .close() on the file object and print "Cleaning up and closing file...". You can verify the file is closed by checking the file_obj.closed attribute.
Test Cases

Use the following test cases to verify your solution works correctly.

Test Case 1: Successful File Read * Input: process_server_logs("system_logs.txt") (where file exists and contains text). * Expected Output: Prints the success message, prints the cleanup message and returns the file's text.

Test Case 2: Standard Flow Control (Missing File) * Input: process_server_logs("missing_logs.txt") (where the file does not exist). * Expected Output: Prints a message indicating the file does not exist (caught by .exists()) and returns None. No exceptions should be raised or caught.

Test Case 3: Custom Error Handling (Empty File) * Input: process_server_logs("empty_logs.txt") (where the file exists but has 0 characters). * Expected Output: Triggers the CorruptedLogError, prints the specific custom error message, prints the cleanup/file closed message, and returns None.

Test Case 4: Developer Error (Bad File Type) * Input: process_server_logs("server_image.png") * Expected Output: The program violently crashes with the AssertionError before opening file, indicating the developer used the wrong file extension.

Loading sandbox workspace environment...

Verify Your Solution

Run assertions against your code in the sandbox environment.

Sandbox Instructions

1. Click Copy Starter Boilerplate at the top to copy function definition.
2. Use the interactive compiler to implement and run your code securely.
3. Click Verify & Submit Solution to validate your code.