L27, 28 Files

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

L27

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:

file = open('filename.txt', 'mode')

filename.txt: Name of the file you want to open.

mode: A string indicating the file access mode. Common modes include:

'r': Read (default mode).

'w': Write (creates a new file or truncates an existing file).

'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').

Reading from a File:

Reading the Entire File:

with open('filename.txt', 'r') as file:

content = file.read()

print(content)

Reading Line by Line:

with open('filename.txt', 'r') as file:

for line in file:

print(line)

Using the readline() method:

file_path = 'example.txt'

with open(file_path, 'r') as file:

# Read the first line

line = file.readline()

# Continue reading lines until the end of the file

while line:

# Process each line as needed

print(line.strip())

# Read the next line

line = file.readline()

The strip() method is used to remove leading and trailing whitespaces from each line.

Writing to a File:

with open('filename.txt', 'w') as file:

file.write('Hello, this is a sample text.')

Appending to a File:
with open('filename.txt', 'a') as file:

file.write('This will be appended to the end.')

Reading and Writing with Context Managers:

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:

file = open('filename.txt', 'r')

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.

# Create a text file and write some lines

with open('sample.txt', 'w') as file:

file.write('Hello, this is line 1.\n')

file.write('And here is line 2.\n')

file.write('This is the third line.\n')

# Open the file, read its contents, and display them

with open('sample.txt', 'r') as file:

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.

Advantages of Using Exceptions:

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:

# Code that may raise an exception

result = 10 / 0 # This will raise a ZeroDivisionError

except ZeroDivisionError:

# Handle the specific exception

print("Division by zero is not allowed.")

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:

print("Division by zero is not allowed.")

except Exception as e:

print(f"An error occurred: {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:

print("Division by zero is not allowed.")

finally:

print("This block always executes.")

Handling multiple exceptions:

You can handle multiple exceptions by using multiple except blocks.

try:

value = int("abc")
except ValueError:

print("Invalid value. Please enter a number.")

except ZeroDivisionError:

print("Division by zero is not allowed.")

except Exception as e:

print(f"An error occurred: {e}")

Using else block:

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:

print("Division by zero is not allowed.")

else:

print("The result is:", result)

Example:

try:

num1 = int(input("Enter the numerator: "))

num2 = int(input("Enter the denominator: "))

result = num1 / num2

print("Result:", result)

except ValueError:

print("Invalid input. Please enter a valid number.")

except ZeroDivisionError:

print("Division by zero is not allowed.")

except Exception as e:

print(f"An error occurred: {e}")

You might also like