Python Programming Concepts: Exception Handling, File Handling, and Serialization

TrustedProbability avatar
TrustedProbability
·
·
Download

Start Quiz

Study Flashcards

18 Questions

What type of exception is caught in the except FileNotFoundError block?

FileNotFoundError

Which function is responsible for creating a directory and writing test data to a file?

handle_files()

What is the purpose of the eval() function used in the handle_exceptions() function?

To execute the lines of code in the 'file.txt' file

What is the purpose of the pickle.dump() and pickle.load() functions used in the serialize_objects() function?

To serialize a Python object to a file and deserialize it from the file

What is the purpose of the json.dumps() and json.loads() functions used in the serialize_objects() function?

To serialize a Python dictionary to a JSON string and deserialize the JSON string back to a dictionary

What is the purpose of the os.path.exists() function used in the handle_files() function?

To check if a file or directory exists in the file system

What is the key difference between Pickling and JSON serialization in Python?

Pickling can store a broader range of object types, while JSON serialization is limited to certain types.

Which function in the pickle module writes a pickled representation of an object to a binary file?

pickle.dump()

In Python, what is the primary purpose of exception handling?

To handle unexpected runtime errors gracefully

What type of serialization format is JSON in Python?

Human-readable text

Which function in the pickle module reads a pickled object from a binary file and returns its de-serialized version?

pickle.load()

What is the purpose of Python's json.loads() function?

Deserialize a JSON-formatted string

Which statement about pickling in Python is correct?

Pickling uses the pickle module to convert Python objects into a binary format.

Which function from the pickle module is used to deserialize a pickled byte stream into a Python object?

pickle.load()

What is the purpose of exception handling in Python programming?

To handle errors and prevent program crashes when unexpected situations occur.

Which arithmetic operation in Python follows the standard order of operations (PEMDAS)?

$2 * (5 + 3)$

Which statement about the json module in Python is true?

The json module is used for serializing and deserializing Python objects into a human-readable JSON format.

What is the purpose of the try and except blocks in Python's exception handling?

The try block is used to define the code that may raise an exception, and the except block is used to handle the exception if it occurs.

Study Notes

import os
import json

def handle_exceptions():
    try:
        f = open('file.txt')
        lines = f.readlines()
        for line in lines:
            result = eval(line)
            print(result)
    except FileNotFoundError:
        print("File not found!")
    except ZeroDivisionError:
        print("Zero division error!")
    except NameError:
        print("Name error!")

def handle_files():
    # Check if the file exists before opening it
    if os.path.exists('file.txt'):
        with open('file.txt', 'r') as file:
            content = file.read()
            print(content)
    else:
        print("File does not exist!")

## Create a directory and write some test data to a file
if not os.path.exists('testdir'):
    os.mkdir('testdir')
with open('testdir/test.txt', 'w') as file:
    file.write('Hello, world!')

def serialize_objects():
    # Serialize a simple Python dictionary using pickle
    import pickle
    data = {'key': 'value'}
    with open('serialized.pickle', 'wb') as output_file:
        pickle.dump(data, output_file)
        
    # Deserialize the saved pickle file
    with open('serialized.pickle', 'rb') as input_file:
        loaded_data = pickle.load(input_file)
        print(loaded_data['key'])
    
    # Serialize a complex Python object using JSON
    import json
    import json
    class MyClass:
        def __init__(self, arg1, arg2):
            self.arg1 = arg1
            self.arg2 = arg2
    my_instance = MyClass(42, 'hello')
    serialized_json = json.dumps(my_instance.__dict__)
    print(serialized_json)
    
    # Deserialize the saved JSON string
    deserialized_obj = json.loads(serialized_json)
    print(deserialized_obj)

This code demonstrates various aspects of Python programming, covering exception handling, file handling, object serialization with pickling, and JSON serialization. It includes functions for handling exceptions, checking file existence, creating directories, and writing/reading contents. Additionally, there are examples of serializing and deserializing objects using pickle and JSON formats.

Explore Python programming concepts like exception handling, file handling, pickling, and JSON serialization with this code snippet. Learn about handling exceptions, checking file existence, creating directories, reading/writing file contents, and serializing/deserializing objects.

Make Your Own Quizzes and Flashcards

Convert your notes into interactive study material.

Get started for free
Use Quizgecko on...
Browser
Browser