Professional Documents
Culture Documents
Unit - 2
Unit - 2
Unit - 2
Chapter – 1 (Files)
Closing a File: It's important to close the file using the close() method
when you are done. This ensures that any pending data is written to the
file, and it frees up system resources.
file.close() # Close the file when you're done
File Modes: File modes allow you to specify how you intend to interact
with the file. Common modes include 'r' for reading, 'w' for writing
(creates a new file or truncates an existing one), and 'a' for appending
(creates a new file or appends to an existing one). You can also use
modes like 'rb' and 'wb' for binary files.
Error Handling: It's good practice to use error handling (e.g., try and
except blocks) to handle potential issues when working with files, like file
not found errors or permission issues.
if os.path.isdir('directory_to_check'):
print('It is a directory')
else:
print('It is not a directory')
readline(size=-1): Reads and returns the next line from the file. If size is
specified, it reads up to that number of bytes.
line = file.readline() # Reads the next line
partial_line = file.readline(20) # Reads up to the next 20 bytes or until
the end of the line
readlines(hint=-1): Reads and returns a list of lines from the file. If hint is
specified, it reads at most hint bytes, seeking the end of the line
lines = file.readlines() # Reads all lines into a list
partial_lines = file.readlines(100) # Reads lines up to the next 100
bytes or until the end of the line
write(string): Writes the specified string to the file. This method is used
when the file is opened in write ('w') or append ('a') mode.
with open('output.txt', 'w') as file:
file.write("Hello, World!")
writelines(lines): Writes a list of lines to the file. Each line in the list
should end with a newline character if necessary.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as file:
file.writelines(lines)
close(): Closes the file, releasing system resources. It's important to close
the file explicitly when you are done with it.
File.close()
flush(): Flushes the internal buffer to the file. This ensures that any data
you've written is actually saved to the file.
file.flush()
import os
path = "/path/to/your/file.txt"
if os.path.exists(path):
print(f"File name: {os.path.basename(path)}")
print(f"File size: {os.path.getsize(path)} bytes")
if os.path.isfile(path):
print("This is a regular file.")
elif os.path.isdir(path):
print("This is a directory.")
if os.access(path, os.R_OK):
print("The file is readable.")
python my_script.py
if __name__ == "__main__":
source_file = 'source.txt' # Replace with the path to your source file
destination_file = 'destination.txt' # Replace with the path to your
destination file
copy_file(source_file, destination_file)
Chapter – 2 (Exceptions)
The try block is used to enclose the code that might raise an
exception.
If an exception occurs in the try block, Python looks for an except
block that can handle that particular type of exception.
You can specify the type of exception to be handled in the except
block. If the exception raised matches the type specified in the except
block, the code inside the except block is executed.
2. Handling Multiple Exceptions:
You can handle multiple exceptions using multiple except blocks or a
single except block with multiple exception types:
try:
# Code that might raise an exception
# ...
except (FirstException, SecondException):
# Code to handle the first or second exception
# ...
except ThirdException:
# Code to handle the third exception
# ...
In this example, the open() function returns a file object that acts as a
context manager. The with statement ensures that the file is properly
closed after the block of code is executed, even if an exception occurs.
Python's standard library provides the contextlib module, which
includes utilities for working with context managers. It also offers the
@contextmanager decorator, which can convert a generator function
into a context manager.
Topic – Exceptions as strings
o In Python, you can catch and handle exceptions as strings by using the
traceback module.
o This technique is helpful when you want to obtain detailed information
about an exception, including the traceback and the context in which it
occurred, and then handle it as a string for logging or other purposes.
Here's an example of how to catch and handle exceptions as strings:
import traceback
try:
a=5
b=0
result = a / b
except Exception as e:
error_message = traceback.format_exc()
print(f"An exception occurred: {error_message}")
if x < 0:
raise ValueError("x cannot be negative.")
In this example, the ValueError is raised with a custom error message if the
value of x is negative.
Raising Custom Exceptions:
You can also create custom exceptions by subclassing the built-in Exception
class. This allows you to define your own exception types that suit your
application's specific needs.
class CustomError(Exception):
pass
def do_something():
raise CustomError("This is a custom error.")
try:
do_something()
except CustomError as e:
print(f"Custom error occurred: {e}")
In this example, the CustomError class is defined by inheriting from the built-in
Exception class.
The do_something() function raises this custom exception, and the except
block catches and handles it appropriately.
Topic – Assertions
In Python, an assertion is a statement that you can use to test if a
condition is true or not.
It is primarily used during the development and debugging phase to
identify and fix bugs in the code.
The assert statement takes an expression and an optional message. If
the expression evaluates to false, the program will raise an
AssertionError with the specified message.
If the expression is true, the program will continue its execution.
The basic syntax for an assert statement in Python is:
assert expression, message
If the value of x is not 5, the assert statement will raise an AssertionError with
the message "x should be 5".
In this example:
We define a custom exception class CustomError that inherits from the
base Exception class.
The __init__ method is used to initialize the exception with a custom
error message.
We define a function check_value that raises the CustomError if the
input value is negative.
In the try block, we call the check_value function with a negative value.
If the value is negative, the CustomError is raised.
We handle the CustomError in the except block and print the custom
error message.
# Global namespace
x = 10
def example_function():
# Local namespace
y=5
print(f'Local variable y: {y}')
example_function()
print(f'Global variable x: {x}')
# Using the built-in namespace
z = len([1, 2, 3, 4, 5])
print(f'Built-in function len(): {z}')
You can then access functions and classes from the math module using
dot notation, like math.sqrt() or math.sin().
2. Importing Specific Items: You can import specific functions or classes
from a module using the from...import statement.
For example:
from math import sqrt, sin
This allows you to use the sqrt() and sin() functions directly without
referencing the module name.
3. Importing with an Alias: You can import a module with an alias to
simplify the name.
For example:
import math as m
You can then use the alias to access functions from the math module,
like m.sqrt() or m.sin().
4. Importing All Items: You can import all items from a module using the
from...import * statement.
For example:
from math import *
This allows you to use all the functions defined in the math module,
However, this approach is generally discouraged because it can lead to
naming conflicts and make the code less readable.
This allows you to use the specific attribute directly without referencing
the module name.
2. Importing All Attributes: If you want to import all attributes from a
module, you can use the from...import * statement.
For example:
from module_name import *
This allows you to use the alias to reference the attribute instead of its
original name.
6. Module Aliasing: You can provide aliases for modules or import specific
functions/classes from modules using aliases, making it easier to
reference them in your code.