

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















In Python, working with files and handling errors are two essential skills every developer must learn. Whether you’re reading data from files or writing logs, things can go wrong — and that’s where exception handling in Python becomes crucial. What is File Handling? ❖ It is the process of storing, retrieving and manipulating data inside a file directly from your Python code. Types of File ❖ Text File ❖ Binary File ❖ CSV File ❖ JSON File
➢ Stores data in ASCII or UNICODE format ➢ Each Character occupies 1 Byte of space. ➢ It is readable/ understandable by user ➢ Each line is terminated by EOL character, it is generally ‘\n’ or ’\r’.
➢ Comma Separated Value File ➢ Each Value in a line is Separated by Delimiter(‘,’) ➢ CSV is used to store Tabular data, such as spreadsheet or database. ➢ CSV Files uses comma as Delimiter, but python can r/w files with any type of Delimiter. ➢ CSV Files can be imported to and exported from programs that store data in tables, eg
File_handle = open(‘path’, ‘mode’) ➢ Open is a function used to open a File ➢ Path of the file is location of file in the systems ➢ Mode of the file is passed according to the operations. ➢ File is accessed through the file handle
File_handle = open(‘path’, ‘mode’) ➢ file_handle holds reference of the file opened ➢ All operation are performed through File Handle. ➢ File Handle is also called File Object ➢ It is just a variable/ identifier and can be named as required.
File_handle = open(‘path’, ‘mode’) #Perform Operation File_handle.clode() Clode() function pushes all the changes to the file
Count Char in a text file Count line in a text file Count Word in a text file Count alphabets, digits, spaces and special character in file Count alphabets, digits, spaces and special character in each line of file Count vowels and consonants in a text file Count vowels and consonants in each line of the file Count words containing vowels in a file.
write(“data”) – writes given data in the file writelines() - writes each element of list as a line in the file
Copy data form file “a” to file “b” Read file “a” and write number of words in file “b” Read file “a” and write it in file “b” in title format Read file “a” and write each word in separate line in “b” Copy data form file “a” to file “b” and add line number in file “b” Copy data form file “a” to file “b” and capitalize each line Capy data form file “a” to “b” after replacing alphabets with “*” , digits with “#”, space with “_”
➢ Import CSV module ➢ Open File in Appropriate Mode ➢ Both R/W operation are performed through Reader/ Writer Objects ➢ Create Reader/ Writer Objects with CSV Module ➢ Performs Read/Write Operations ➢ Close File
➢ Import CSV module ➢ Open File in READ Mode ➢ Creat Reader Objects with CSV Module ➢ Data is in READER Object ➢ Read form READER Object ➢ Close File
➢ Import CSV module ➢ Open File in WRITE/APPEND Mode ➢ Create WRITER Objects with desired DELIMITER ➢ Writerow(row): writes a row in CSV file ➢ Writerows( 2 D Data): writes multiple rows in CSV file ➢ Close File
Exception Handling is a technique used to handle errors that occur during program execution without crashing the program. Example Without Exception Handling: num = int(input("Enter a number: ")) result = 10 / num print(result) If the user enters: 0 Output: ZeroDivisionError: division by zero The program stops immediately .
What is an Exception? An exception is an error that occurs while a program is running. Common Exceptions in Python Exception Description ZeroDivisionError Dividing by zero ValueError Invalid value entered TypeError Wrong data type used IndexError Invalid list index KeyError Accessing non-existent dictionary key FileNotFoundError File does not exist NameError (^) Variable not defined
Using else Block The else block runs when no exception occurs. Syntax try:
except:
else:
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Cannot divide by zero!") else: print("Result:", result) Example: Input: 2 Output: Result: 5.
Using finally Block The finally block always executes whether an exception occurs or not. Syntax try:
except:
finally:
try: num = int(input("Enter a number: ")) print( 10 / num) except ZeroDivisionError: print("Cannot divide by zero!") finally: print("Program ended.") Example Output Cannot divide by zero! Program ended.