Docsity

File Handling and Exceptions, Lecture notes of Programming Languages

Toggle sidebar
bg1
Ngawang T
File Handling and Exceptions
Unit VI
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download File Handling and Exceptions and more Lecture notes Programming Languages in PDF only on Docsity!

Unit VI File Handling and Exceptions

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

Text 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’.

CSV File

➢ 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

  • MS Excel

Opening File

SYNTAX:

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

SYNTAX:

File Handling

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.

Closing File

SYNTAX:

File_handle = open(‘path’, ‘mode’) #Perform Operation File_handle.clode() Clode() function pushes all the changes to the file

Exercise

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.

Writing in File

write(“data”) – writes given data in the file writelines() - writes each element of list as a line in the file

Exercise

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 “_”

CSV Module

➢ 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

Read CSV 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

Writing in CSV 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

Writing in CSV File

Exception Handling in Python

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:

risky code

except:

handle error

else:

run if no error

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:

code

except:

error handling

finally:

always executes

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.