What is the difference between read(), readline(), and readlines()?

In Python, read(), readline(), and readlines() are methods of a file object that allow you to read data from a file, but they work in slightly different ways:

1. read()

  • Functionality: Reads the entire content of a file as a single string.
  • Use Case: Use it when you want to read the whole file at once.
  • Example: with open('example.txt', 'r') as file: content = file.read() print(content)
  • Note: Be cautious when working with large files, as it loads the entire file into memory.

2. readline()

  • Functionality: Reads the next line from the file (up to and including the newline character).
  • Use Case: Use it when you want to read a file line by line interactively.
  • Example: with open('example.txt', 'r') as file: line = file.readline() while line: print(line, end='') # Print each line without adding extra newline line = file.readline()
  • Note: If the file ends, readline() returns an empty string ('').

3. readlines()

  • Functionality: Reads all lines from the file and returns them as a list of strings, where each string is a line.
  • Use Case: Use it when you want to process all lines of a file but as a list.
  • Example: with open('example.txt', 'r') as file: lines = file.readlines() for line in lines: print(line, end='') # Print each line without adding extra newline
  • Note: This also reads the entire file into memory, similar to read().

Summary of Differences:

MethodReadsReturnsUse Case
read()Entire fileStringWhen you need the whole file content.
readline()One line at a timeStringWhen you want to process lines interactively.
readlines()Entire fileList of stringsWhen you want all lines but as a list.

For large files, it’s better to use readline() or iterate over the file object directly (e.g., for line in file:) to avoid memory issues.

How do you raise and handle custom exceptions?

Raising and Handling Custom Exceptions in Python

Python allows you to define and use custom exceptions by subclassing the built-in Exception class. This is useful when you want to create meaningful, domain-specific error types in your program.


1. Raising a Custom Exception

To raise a custom exception:

  1. Define a new exception class by inheriting from the Exception class (or any subclass of Exception).
  2. Use the raise keyword to trigger the exception.

Example:

# Define a custom exception
class CustomError(Exception):
    pass

# Raise the custom exception
def risky_function():
    raise CustomError("This is a custom exception!")

# Call the function
try:
    risky_function()
except CustomError as e:
    print(f"Caught an error: {e}")

Output:

Caught an error: This is a custom exception!

2. Adding Additional Attributes

Custom exceptions can include attributes and methods to provide more context about the error.

Example:

class ValidationError(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code

try:
    raise ValidationError("Invalid input", 400)
except ValidationError as e:
    print(f"Error: {e}, Code: {e.code}")

Output:

Error: Invalid input, Code: 400

3. Handling Custom Exceptions

You handle custom exceptions just like any other exception using try-except.

Example:

class NegativeValueError(Exception):
    pass

def check_positive(value):
    if value < 0:
        raise NegativeValueError("Negative values are not allowed!")

try:
    check_positive(-5)
except NegativeValueError as e:
    print(f"Error: {e}")

Output:

Error: Negative values are not allowed!

4. Custom Hierarchies of Exceptions

You can define a hierarchy of exceptions for better organization.

Example:

class AppError(Exception):
    """Base class for all application-related errors."""
    pass

class DatabaseError(AppError):
    pass

class NetworkError(AppError):
    pass

try:
    raise DatabaseError("Database connection failed!")
except DatabaseError as e:
    print(f"Database error: {e}")
except NetworkError as e:
    print(f"Network error: {e}")
except AppError as e:
    print(f"General app error: {e}")

Output:

Database error: Database connection failed!

5. Combining Custom Exceptions with Standard Exceptions

You can handle custom and standard exceptions together.

Example:

class CustomError(Exception):
    pass

try:
    x = int("abc")  # Raises a ValueError
    raise CustomError("Custom error occurred")
except ValueError as e:
    print(f"Value error: {e}")
except CustomError as e:
    print(f"Custom error: {e}")

Output:

Value error: invalid literal for int() with base 10: 'abc'

Best Practices

  1. Use meaningful names for custom exceptions to make them self-explanatory.
  2. Add relevant attributes to pass additional error details.
  3. Group related exceptions under a common base class for better organization.
  4. Always use try-except to gracefully handle your custom exceptions in the program.

By using custom exceptions effectively, you can improve the readability, maintainability, and robustness of your code.