L27, 28 Files
L27, 28 Files
File handling:
File handling in Python refers to the operations that can be performed on files, such as reading from a
file, writing to a file, and manipulating file-related attributes. Python provides built-in functions and
methods that make it easy to work with files.
Advantages:
Data Storage: Files provide a means to store data persistently. Data can be stored in files and retrieved
later, allowing for data persistence between program runs.
Data Retrieval: Files allow you to read and retrieve data stored in a structured manner. This is essential
for working with large datasets or configurations.
Data Sharing: Files serve as a common medium for sharing data between different programs or
systems. Data can be written to a file in one program and read from the same file in another program.
Disadvantages:
Security Concerns: File operations can pose security risks. Improper handling of file paths, incorrect
permissions, or careless file operations can lead to security vulnerabilities.
Platform Dependencies: File paths and file handling mechanisms may vary across different operating
systems. Writing platform-independent file-handling code requires careful consideration.
Error Handling: File operations can result in errors (e.g., file not found, permission denied). Proper
error handling is necessary to handle these situations gracefully.
File Operations:
File handling in Python involves various operations such as opening, reading, writing, and closing files.
Here's a more detailed explanation of file handling in Python:
Opening a File:
To open a file, you use the open() function. The basic syntax is:
mode: A string indicating the file access mode. Common modes include:
'a': Append (opens the file for writing at the end, creating the file if it doesn't exist).
'b': Binary mode (e.g., 'rb' or 'wb').
content = file.read()
print(content)
print(line)
file_path = 'example.txt'
line = file.readline()
while line:
print(line.strip())
line = file.readline()
The strip() method is used to remove leading and trailing whitespaces from each line.
Writing to a File:
Appending to a File:
with open('filename.txt', 'a') as file:
Using the with statement is recommended as it ensures that the file is properly closed after the
operations are performed.
Closing a File:
When you're done with a file, it's good practice to close it using the close() method:
content = file.read()
file.close()
Deleting a File:
You can use the os.remove() function from the os module to delete a file:
import os
os.remove('filename.txt')
Create a text file named "sample.txt" and write a few lines of text to it. Write a Python program to
open the file, read its contents, and display them.
contents = file.read()
print("Contents of 'sample.txt':")
print(contents)
L28
EXCEPTION HANDLING
An exception is an event that occurs during the execution of a program that disrupts the normal flow
of instructions. When a Python script encounters an exceptional situation, it raises an exception.
Exceptions can occur for various reasons, such as errors in the code, unexpected input, or external
factors like file I/O errors.
Error Handling: Exception handling provides a structured way to handle errors in your code. Instead
of letting the program crash when an error occurs, you can catch and handle exceptions, allowing the
program to continue its execution.
Graceful Termination: Exceptions allow you to terminate a script or function gracefully in the face of
unexpected errors. You can catch exceptions and take appropriate actions rather than abruptly ending
the program.
Debugging: When an exception is raised, Python provides a traceback that includes information about
where the exception occurred. This traceback can be immensely helpful for debugging, as it shows the
sequence of calls that led to the error.
Robustness: Exception handling enhances the robustness of your code. By anticipating and handling
potential errors, you make your program more resilient to unexpected conditions, improving its overall
reliability.
Separation of Concerns: Exception handling allows you to separate error-handling code from the
normal flow of your program. This makes your code cleaner and more readable by isolating error-
related logic.
Exception handling involves the use of the try, except, and finally blocks. Here's a brief explanation of
these components:
try block:
The code that might raise an exception is placed inside the try block.
If an exception occurs within the try block, the interpreter looks for an appropriate except block to
handle the exception.
try:
except ZeroDivisionError:
except clause:
An except block follows the try block and specifies the type of exception it can handle.
If an exception of the specified type occurs in the try block, the corresponding except block is executed.
try:
result = 10 / 0
except ZeroDivisionError:
except Exception as e:
finally block:
The finally block is optional and is used to define cleanup code that will be executed no matter what,
whether an exception occurred or not.
try:
result = 10 / 2
except ZeroDivisionError:
finally:
try:
value = int("abc")
except ValueError:
except ZeroDivisionError:
except Exception as e:
An optional else block can be used after all except blocks. It is executed only if no exceptions are raised
in the try block.
try:
result = 10 / 2
except ZeroDivisionError:
else:
Example:
try:
print("Result:", result)
except ValueError:
except ZeroDivisionError:
except Exception as e: