0% found this document useful (0 votes)
13 views5 pages

Session 5 - Summary 1718363016202

Uploaded by

dhanaamadasani1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

Session 5 - Summary 1718363016202

Uploaded by

dhanaamadasani1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

IIDT – Blackbucks Short Term Internships AIML Session

05 _ APSCHE

Python Files and File Operations:


Types of Python Files
In Python, files are generally classified into two main types based on their content and
structure:

Text Files: These files contain text data and are human-readable. Examples include .txt, .csv,
and .json files. They store data in a structured format, often with lines and characters.
Binary Files: These files contain data in a format that is not human-readable and is intended
to be interpreted by programs. Examples include .bin, .jpg, .png, and .dat files. They store
data in binary form (0s and 1s).

File Operations in Python


Python provides several built-in functions and methods to handle file operations. The most
common operations include:
Opening a File: Use the open() function to open a file.
Reading from a File: Use methods like read(), readline(), or readlines() to read data from a
file.
Writing to a File: Use methods like write() or writelines() to write data to a file.
Closing a File: Always close a file after operations using the close() method.

File Modes in Python


'r': Read (default mode). Opens the file for reading.
'w': Write. Opens the file for writing (creates a new file or truncates an existing file).
'a': Append. Opens the file for appending data.
'b': Binary mode. Used with other modes for binary files (rb, wb, ab).
't': Text mode (default). Used with other modes for text files (rt, wt, at)
Ex: Opening and Reading a Text File
# Open a file in read mode

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

# Read the entire content of the file

content = file.read()

print(content)

# Close the file

file.close()

Ex: Writing to a Text File


# Open a file in write mode (creates a new file if it doesn't exist)

file = open('example.txt', 'w')

# Write data to the file

file.write('Hello, World!\n')

file.write('This is an example of writing to a text file.')

# Close the file

file.close()

Ex: Appending to a Text File


# Open a file in append mode

file = open('example.txt', 'a')

# Append data to the file

file.write('\nAppending a new line to the file.')

# Close the file


file.close()

Errors and Exception Handling in Python:

In Python, errors and exceptions are events that disrupt the normal flow of a program's
execution. Understanding how to handle these exceptions is crucial for creating robust and
reliable programs.

Syntax Errors: These occur when the parser detects an incorrect statement. For example,
missing colons, incorrect indentation, or misspelled keywords.
Ex:
# Syntax Error Example
if True
print("This will cause a syntax error")

Exceptions: These are errors detected during execution. Common exceptions include
ZeroDivisionError, FileNotFoundError, TypeError, ValueError, etc.
Ex:
# Exception Example
result = 10 / 0 # This will raise a ZeroDivisionError

Exception Handling
Python provides a way to handle exceptions using try, except, else, and finally blocks.

 try: The block of code to be attempted (may lead to an error).


 except: The block of code to execute if there is an error in the try block.
 else: The block of code to execute if the try block does not raise an exception.
 finally: The block of code to execute regardless of whether an exception was raised or not.

Example: Handling Exceptions

try:

result = 10 / 0

except ZeroDivisionError:

print("You cannot divide by zero!")


Handling Multiple Exceptions:

try:

result = 10 / 0

except ZeroDivisionError:

print("You cannot divide by zero!")

except ValueError:

print("Invalid value!")

Catching All Exceptions

try:

result = 10 / "a"

except Exception as e:

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

Using Else and Finally

try:

result = 10 / 2

except ZeroDivisionError:

print("You cannot divide by zero!")

else:

print("The division was successful:", result)

finally:

print("This block is executed no matter what.")


Raising Exceptions

def check_positive(number):
if number <= 0:
raise ValueError("The number is not positive")
return number

try:
check_positive(-10)
except ValueError as e:
print(e)
 Syntax Errors: Occur when the Python parser detects an incorrect statement.
 Exceptions: Occur during execution, disrupting the normal flow of the program.
 Exception Handling: Use try, except, else, and finally blocks to handle exceptions
and ensure your program can deal with errors gracefully.

You might also like