File I/O and Exception Handling

Welcome to our lesson on File I/O and Exception Handling in Python! If you’re coming from Node.js, you’ll find some familiar concepts here, but Python offers some unique and powerful ways to work with files and handle errors. Let’s dive in and see how Python’s approach compares to what you’re used to in Node.js.

Reading and Writing Files

In Python, working with files is straightforward and often more concise than in Node.js. Let’s look at how we can read from and write to files:

Reading Files

# Python
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
// JavaScript (Node.js)
import { readFile } from 'fs/promises';

readFile('example.txt', 'utf8')
  .then((data) => console.log(data))
  .catch((err) => console.error(err));

Python’s with statement is a powerful feature that ensures the file is properly closed after we’re done with it, even if an exception occurs.

Writing Files

# Python
with open('output.txt', 'w') as file:
    file.write('Hello, Python!')
// JavaScript (Node.js)
import { writeFile } from 'fs/promises';

writeFile('output.txt', 'Hello, JavaScript!', 'utf8')
  .then(() => console.log(`Successfully wrote to ${filename}`))
  .catch((err) => console.error('Error writing to file:', err));

JSON Handling

Both Python and JavaScript have built-in support for JSON, but the syntax differs slightly:

# Python
import json

# Parse JSON string
data = json.loads('{"name": "Alice", "age": 30}')

# Convert to JSON string
json_string = json.dumps(data)
// Parse JSON string in JavaScript
const data = JSON.parse('{"name": "Alice", "age": 30}');

// Convert to JSON string
const jsonString = JSON.stringify(data);

The main difference is that Python uses json.loads() and json.dumps(), while JavaScript uses JSON.parse() and JSON.stringify().

Exception Handling

Python’s exception handling is similar to JavaScript’s, but with some key differences:

# Python
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
else:
    print("No error occurred")
finally:
    print("This always runs")
// JavaScript
try {
  const result = 10 / 0;
} catch (e) {
  console.error(`Error: ${e}`);
} finally {
  console.log('This always runs');
}

Key differences:

  • Python uses except instead of catch
  • Python allows you to specify the type of exception to catch
  • Python has an else clause that runs if no exception occurs

Creating Custom Exceptions

In Python, you can create custom exceptions by inheriting from the Exception class:

# Python
class CustomError(Exception):
    pass

try:
    raise CustomError("This is a custom error")
except CustomError as e:
    print(f"Caught custom error: {e}")

In JavaScript, you would typically use the Error constructor:

// JavaScript
class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = 'CustomError';
  }
}

try {
  throw new CustomError('This is a custom error');
} catch (e) {
  if (e instanceof CustomError) {
    console.log(`Caught custom error: ${e.message}`);
  }
}

Conclusion

In this lesson, we’ve explored how Python handles file I/O and exceptions, comparing it to Node.js approaches. We’ve seen that Python often provides more concise and readable ways to perform these operations, especially with features like the with statement and specific exception types.

Next up, we’ll dive into functional programming in Python, where we’ll explore how Python’s approach to functions and functional programming concepts compares to JavaScript’s. Get ready to see how Python’s unique features can enhance your programming toolkit!