0% found this document useful (0 votes)
14 views8 pages

Python File I/O and Exception Handling Guide

The document discusses file I/O in Python, explaining how to open, read, write, and close files, as well as the importance of proper file management. It also covers exceptions and assertions, detailing how to handle exceptions using try-finally and describing five built-in exceptions with examples. Additionally, the document defines classes and objects, encapsulation, and multiple inheritance in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Python File I/O and Exception Handling Guide

The document discusses file I/O in Python, explaining how to open, read, write, and close files, as well as the importance of proper file management. It also covers exceptions and assertions, detailing how to handle exceptions using try-finally and describing five built-in exceptions with examples. Additionally, the document defines classes and objects, encapsulation, and multiple inheritance in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1. Discuss file I/O in Python. How to perform open, read, write, and close into a file?

Write a Python
program to read a file line-by-line store it into a variable.

Ans.

File I/O:

1. A file in a computer is a location for storing some related data.


2. It has a specific name.
3. The files are used to store data permanently on to a non-volatile memory (such as hard disks).
4. As we know, the Random Access Memory (RAM) is a volatile memory type because the data in it is lost when we turn off the computer. Hence, we use
files for storing of useful information or data for future reference.

Open, read, write and close into a file:

Open into a file

1. Python has a built-in open() function to open files from the directory.
2. Two arguments that are mainly needed by the open() function are:
1. File name: It contains a string type value containing the name of the file which we want to access.
2. Access_mode: The value of access_mode specifies the mode in which we want to open the file, i.e., read, write, append etc.
3. Syntax:

1.

close into a file

1. When the operations that are to be performed on an opened file are finished, we have to close the file in order to release the resources.
2. Python comes with a garbage collector responsible for cleaning up the unreferenced objects from the memory, we must not rely on it to close a file.
3. Proper closing of a file frees up the resources held with the file.
4. The closing of file is done with a built-in function close().
5. Syntax:

write into a file

1. After opening a file, we have to perform some operations on the file. Here we will perform the write operation.
2. In order to write into a file, we have to open it with w mode or a mode, on any writing-enabling mode.
3. We should be careful when using the w mode because in this mode overwriting persists in case the file already exists.
4. For example:

The given example creates a file named [Link] if it does not exist, and overwrites into it if it exists. If we open the file, we will find the following content in
it.
Output:
Writing to the file line 1
Writing to the file line 2
Writing to the file line 3
Writing to the file line 4

Reading into a file

1. In order to read from a file, we must open the file in the reading mode (r mode).
2. We can use read (size) method to read the data specified by size.
3. If no size is provided, it will end up reading to the end of the file.
4. The read() method enables us to read the strings from an opened file.
5. Syntax :
file object. read ([size])
For example:
# open the file

Q2. Discuss exceptions and assertions in Python. How to

handle exceptions with try-finally? Explain five built-in exceptions with example?

Ans.

Exception:

1. While writing a program, we often end up making some errors. There are many types of error that can occur in a program.
2. The error caused by writing an improper syntax is termed syntax error or parsing error; these are also called compile time errors.
3. Errors can also occur at runtime and these runtime errors are known as exceptions.
4. There are various types of runtime errors in Python.
5. For example, when a file we try to open does not exist, we get a FileNotFoundError. When a division by zero happens, we get a ZeroDivisionError. When
the module we are trying to import does not exist, we get an ImportError.
6. Python creates an exception object for every occurrence of these run- time errors.
7. The user must write a piece of code that can handle the error.
8. If it is not capable of handling the error, the program prints a trace back to that error along with the details of why the error has occurred.
Assertions:

1. An assertion is a sanity-check that we can turn on or turn off when we are done with our testing of the program. An expression is tested, and if the result is
false, an exception is raised.
2. Assertions are carried out by the assert statement.
3. Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.
4. An AssertionError exception is raised if the condition evaluates to false.
5. The syntax for assert is: assert Expression [, Arguments]
6. If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.

Handle exceptions:

1. Whenever an exception occurs in Python, it stops the current process and passes it to the calling process until it is handled.
2. If there is no piece of code in our program that can handle the exception, then the program will crash.
3. For example, assume that a function X calls the function Y, which in turn calls the function Z, and an exception occurs in Z. If this exception is not handled
in Z itself, then the exception is passed to Y and then to X. If this exception is not handled, then an error message will be displayed and our program will
suddenly halt.
1. Try…except:
1. Python provides a try statement for handling exceptions.
2. An operation in the program that can cause the exception is placed in the try clause while the block of code that handles the exception is placed in the except
clause.
3. The block of code for handling the exception is written by the user and it is for him to decide which operation he wants to perform after the exception has been
identified.
4. Syntax:

2. Try finally :
1. The try statement in Python has an optional finally clause that can be associated with it.
2. The statements written in the finally clause will always be executed by the interpreter, whether the try statement raises an exception or not.
3. With the try clause, we can use either except or finally, but not both.
4. We cannot use the else clause along with the final clause.

Five built-in exceptions:

1. exception LookupError: This is the base class for those exceptions that are raised when a key or index used on a mapping or sequence is invalid or not
found. The exceptions raised are:
1. KeyError
2. IndexError

2. TypeError: TypeError is thrown when an operation or function is applied to an object of an inappropriate type.

3. exception ArithmeticError: This class is the base class for those built-in exceptions that are raised for various arithmetic errors such as:
1. OverflowError
2. ZeroDivisionError
3. Floating PointError
4. For example:

4. exception AssertionError: An AssertionError is raised when an assert statement fails.

5. exception AttributeError: An AttributeError is raised when an attribute reference or assignment fails such as when a non-existent attribute is referenced.
Q3. Define Class Object with Examples?

Ans.

Class:

1. A class can be defined as a blue print or a previously defined structure from which objects are made.
2. Classes are defined by the user; the class provides the basic structure for an object.
3. It consists of data members and method members that are used by the instances of the class.
4. In Python, a class is defined by a keyword Class.
5. Syntax: class class_name;
6. For example: Fruit is a class, and apple, mango and banana are its objects. Attribute of these objects are color, taste, etc.

In the given example, we have created a class Student that contains two methods: fill_details and print_details. The first method fill_details takes four arguments:
self, name, branch and year. The second method print_details takes exactly one argument: self.

Objects:

1. An object is an instance of a class that has some attributes and behavior.


2. The object behaves according to the class of which it is an object.
3. Objects can be used to access the attributes of the class.
4. The syntax of creating an object in Python is similar to that for calling a function.
5. Syntax :
obj_name = class_name()
For example:
s1 = Student ()
In the given example, Python will create an object s1 of the class student.
Q4. Explain data encapsulation with example.

Ans.

1. In Python programming language, encapsulation is a process to restrict the access of data members. This means that the internal details of an object may
not be visible from outside of the object definition.
2. The members in a class can be assigned in three ways i.e., public, protected and private.
3. If the name of a member is preceded by single underscore, it is assigned as a protected member.
4. If the name of a member is preceded by double underscore, it is assigned as a private member.
5. If the name is not preceded by anything then it is a public member.

Name Notation Behavior

varname Public Can be accessed from anywhere

_varname Protected They are like the public member buy they cannot be directly accessed from outside

__varname Private They cannot be seen and accessed from outside the class
Q5. What do you mean by multiple inheritance? Explain in detail.

Ans.

1. In multiple inheritance, a subclass is derived from more than one base class.
2. The subclass inherits the properties of all the base classes.
3. In Fig. subclass C inherits the properties of two base classes A and B.

4. Syntax

Common questions

Powered by AI

Common built-in exceptions in Python assist in runtime error handling by identifying typical errors that can occur during program execution and helping developers manage these errors gracefully. Examples include: - **FileNotFoundError**: Raised when a file specified is not found. - **ZeroDivisionError**: Raised when division by zero is attempted. - **ImportError**: Raised when an import statement fails due to missing modules. - **TypeError**: Raised when an operation or function is applied to a wrong type. - **IndexError**: Raised when attempting to access an index that is out of range in a list. These exceptions help identify what went wrong, allowing developers to implement corrective logic in the form of exception handlers .

Implementing classes in Python involves defining a blueprint from which objects can be created, encapsulating data attributes and methods. Using the keyword 'class', developers can structure code to utilize object-oriented principles such as encapsulation, inheritance, and polymorphism. Classes hold data members and methods that operate on the data, facilitating reusability and modular design. This allows for flexible and scalable architectures, offering clear structures that promote code maintainability and scalability. For instance, a simple class Employee might include methods like add_salary, which changes the internal state of the employee instance without affecting other components. This modular design is a core advantage of object-oriented programming .

In Python's object-oriented programming (OOP) model, classes serve as blueprints for creating objects, encapsulating data and functions that act on data. This organization allows for modular design as classes can represent complex data structures with attributes and behaviors. By promoting inheritance, classes facilitate code reusability, allowing new classes to derive from existing ones, thereby extending or customizing functionality without rewriting code. Instances of a class (objects) ensure that the data and methods were encapsulated logically, making the code easier to manage and extend. This fosters a coding environment that is both efficient and maintainable, aligning with OOP principles like polymorphism and encapsulation .

Multiple inheritance in Python allows a subclass to inherit the attributes and methods of more than one parent class. This can be beneficial as it provides a way to re-use code across multiple classes, potentially reducing redundancy and ensuring that a class can combine behaviors from multiple sources. However, it can also introduce complexity, particularly if the parent classes have methods with the same names (leading to the Diamond Problem), which can cause ambiguity in which method to execute. In Python, this is managed by the Method Resolution Order (MRO) which uses a depth-first, left-to-right rule to resolve conflicts .

Python offers several file modes when opening a file using the open() function, such as 'r' for read, 'w' for write, 'a' for append, 'x' for exclusive creation, and others. The mode alters the behavior of the file object, dictating how the file is accessed. When using write modes like 'w', it's important to remember that this will overwrite the file if it already exists, potentially leading to data loss. Therefore, using 'a' mode, which appends data to the file rather than overwriting, can be a safer choice when preserving existing data is essential. Ensuring backups or confirmations before overwriting files is a precaution against unintentional data loss .

File operations in Python start with opening a file using the open() function, which requires the filename and mode (such as 'r' for reading or 'w' for writing). Once opened, files can be read line-by-line using methods like read() or readline(). For writing, files must be opened in an appropriate mode, and the write() method is used to add content. Finally, closing a file is essential as it frees the memory and system resources used by the file handle. Closing files properly prevents data loss by ensuring all output is flushed to files before closing .

Assertions in Python are primarily used for debugging purposes as sanity checks, and they are intended to be internal self-checks in the code that catch developer errors. By contrast, exceptions are used to handle errors which might occur during normal operation. Assertions are made using the assert statement and throw an AssertionError if the condition is false. This differs from exceptions, which are typically more dynamic checks that prevent the program from crashing due to errors such as division by zero or file not found errors. For example, assertions can verify that variables meet certain constraints during development, ensuring that assumptions hold while developing the code .

Exception handling in Python using try-except allows the program to handle errors gracefully by catching exceptions during the execution of code, which helps maintain the normal flow of the program instead of causing abrupt termination. The try block contains code that might throw an exception, while the except block contains code for handling that exception. Meanwhile, try-finally ensures that the finally block is executed regardless of whether an exception has occurred in the try block, making it useful for cleanup actions. For example, using finally to close a file ensures no resource leak occurs if an exception like FileNotFoundError is raised during file operations .

Encapsulation in Python is a process that restricts access to certain components of an object, thereby creating a protective barrier around the data. This is crucial because it helps in maintaining structure and organization by controlling access, thereby preventing external interference and misuse. Python uses three access specifiers: public, protected, and private. A public member is accessible from anywhere, a protected member (denoted with a single underscore) can be accessed only within the class and its subclasses, and a private member (denoted with a double underscore) cannot be accessed directly outside its class. This ensures that the internal representation of an object is hidden from the outside, adhering to the principle of information hiding .

Python classes can be structured using data encapsulation to restrict access to certain components. To achieve this, public, protected, and private attributes are used. Public members can be accessed from anywhere. Protected members start with a single underscore (e.g., _protected), indicating that they should not be accessed directly outside of subclasses. Private members use a double underscore prefix (e.g., __private) to prevent direct access from outside the class. For instance: ```python class ExampleClass: def __init__(self): self.public = 'I am public' self._protected = 'I am protected' self.__private = 'I am private' example = ExampleClass() print(example.public) # valid print(example._protected) # valid, but indicates it should not be accessed this way # print(example.__private) # throws an AttributeError ```This provides data abstraction and security by preventing unintended interference and misuse .

You might also like