0% found this document useful (0 votes)
2 views

Datetime Filehandling Exception

Uploaded by

krishnakrisha001
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Datetime Filehandling Exception

Uploaded by

krishnakrisha001
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

DateTime

• The datetime module in Python provides classes for manipulating dates and times.
• The datetime module provides several classes, including:
• datetime: Represents a date and time.
• date: Represents a date (year, month, day).
• time: Represents a time (hour, minute, second, microsecond).
datetime Class Methods
• datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0): Creates a datetime object.
Example:
from datetime import datetime
dt = datetime(2024, 4, 16, 10, 30, 0)
print(dt) # Output: 2024-04-16 10:30:00
• date(year, month, day): Creates a date object.
Example:
from datetime import date
d = date(2024, 4, 16)
print(d) # Output: 2024-04-16
time Class Methods
• time(hour=0, minute=0, second=0, microsecond=0): Creates a time object.
Example:
from datetime import time
t = time(10, 30)
print(t) # Output: 10:30:00
• today(): Returns the current local date.
Example:
from datetime import datetime
today = datetime.today()
print(today) # Output: Current date and time
• now(): Returns the current local date and time.
• strftime(format): Returns a string representing the date/time according to the format string.
• strptime(date_string, format): Parses a string representing a date/time into a datetime object.

timedelta Class
• timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0): Represents a
duration.

Example
from datetime import datetime, timedelta
today = datetime.today()
future_date = today + timedelta(days=7)
print(future_date) # Output: Date 7 days from now
Exception Handling
• Exception handling in Python allows you to gracefully manage errors that occur during program execution.
try-except Block
Example
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero")
Multiple Except Blocks
try:
file = open("nonexistent_file.txt", "r")
except FileNotFoundError:
print("Error: File not found")
except IOError:
print("Error: Input/output error")
Handling Multiple Exceptions
try:
age = int(input("Enter your age: "))
except (ValueError, TypeError):
print("Error: Invalid input")

else Block
try:
result = 10 / 2
except ZeroDivisionError:
print("Error: Cannot divide by zero")
else:
print("Result:", result)
finally Block
try:
file = open("data.txt", "r")
# Process the file
except IOError:
print("Error: Input/output error")
finally:
file.close()

Custom Exceptions
class NegativeNumberError(Exception):
def __init__(self, number):
self.number = number
self.message = "Error: Negative number not allowed"
def check_positive(number):
if number < 0:
raise NegativeNumberError(number)
• Raising Exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
Built-in Exceptions
1.SyntaxError: Raised when the Python parser encounters a syntax error.

# Example of SyntaxError

print("Hello, world!)

# SyntaxError: EOL while scanning string literal

2.IndentationError: Raised when there is incorrect indentation in Python code.

# Example of IndentationError

def my_function():

print("Indented statement")

# IndentationError: expected an indented block


3.NameError: Raised when a local or global name is not found.

# Example of NameError

print(my_variable)
# NameError: name 'my_variable' is not defined

4.TypeError: Raised when an operation or function is applied to an object of inappropriate type.

# Example of TypeError

result = 10 / '2'

# TypeError: unsupported operand type(s) for /: 'int' and 'str'

5.ValueError: Raised when a built-in operation or function receives an argument that has the right type but an
inappropriate value.

# Example of ValueError

num = int('abc')
# ValueError: invalid literal for int() with base 10: 'abc'
6.ZeroDivisionError: Raised when division or modulo by zero is performed.
# Example of ZeroDivisionError
result = 10 / 0
# ZeroDivisionError: division by zero

7.FileNotFoundError: Raised when a file or directory is requested but cannot be found.


# Example of FileNotFoundError
with open('nonexistent_file.txt', 'r') as f:
content = f.read()
# FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt’

8.IndexError: Raised when a sequence subscript is out of range.


# Example of IndexError
my_list = [1, 2, 3]
print(my_list[3])
# IndexError: list index out of range
File Handling Operations
• File handling in Python involves performing operations such as reading from and writing to files.

Opening a File
file = open(filename, mode)
filename: Name of the file to be opened.
mode: Specifies the mode in which the file is opened ('r' for reading, 'w' for writing, 'a' for appending, etc.).
Example:
file = open("example.txt", "r")
Reading from a File: Reads the entire contents of the file as a string.
content = file.read()
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Writing to a File: Writes the specified content to the file.
file.write(content)
Example:
with open("output.txt", "w") as file:
file.write("Hello, world!")

Appending to a File: Opens the file in append mode and adds the specified content to the end of the file.
file = open(filename, "a")
file.write(content)
Example:
with open("output.txt", "a") as file:
file.write("\nAppending additional content.")

Closing a File: Closes the file, releasing any system resources associated with it.

file.close()
Example:
file = open("example.txt", "r")
content = file.read()
file.close()

Using with Statement: Automatically closes the file when the block is exited, ensuring proper resource
management.
with open(filename, mode) as file:
# Perform file operations:
Example:
with open("example.txt", "r") as file:
content = file.read()
File Modes:
'r': Read mode (default). Opens the file for reading.
'w': Write mode. Opens the file for writing. If the file exists, it will be overwritten. If the file does not exist, a
new file will be created.
'a': Append mode. Opens the file for appending. New data will be written to the end of the file.
Example:
with open("example.txt", "w") as file:
file.write("Content written in write mode.")

You might also like