D a t e : 2 5 / 5 / 202 3 Capacity Building Program “Professional Development in Python, AI and Data Science” RECAPITULATION Topic: File Handling Purpose to use in Program . T y p e s o f F i le : How to open a text file. File Access Modes. Read data from a File. Write data to a File. Append data to a File Exception Handling
1. Purpose ? Ans.) File helps us to store the data permanently, which can be retrieved for future use. 2 . T y p e s o f F i le : Text Files. Binary Files. CSV Files ……….
3. How to open a text file ? Syntax: FileObject = open(<file name >) OR FileObject = open(< filename / path>,<mode>) e.g. F = open(“demo files.txt”, “r”) F= open(“C:\\Users\\ANNIE\\Desktop”, “r”) F= open(r “C :\Users\ANNIE\Desktop”, “r”) N ote :- r means r a w string
4. File Access Modes
Read From Files : r e a d ( ) : - R eads at mo st n b y t e s ; if n is no t specifi e d r eads the e n ti r e fil e . Returns the read bytes in the form of a string. syntax: <file handle>.read([n ]) e.g. f1.read( ) 6 . W r i te i n to F i l e s : w r i t e ( ) : - write ( ) method takes a string and writes it in the file . For storing data, with EOL character, we have to add ‘\n’ character to the end of the string. For storing numeric value, we have to either convert the value into string using str ( ) or write in quotes. Syntax: < filehandle >.write(values) e.g . f1.write(“ Have a Good Day!”)
7. Append data to a File A file opened in append mode retains its previous data while allowing us to add newer data into. Syntax: filehandle = open(“filename", "a") # append mode < filehandle >.write(values) e.g. f1=open(“demo.txt”, “a”) f1.write(“Welcome”)
8. Exception Handling Exception : Generally exception generates during the execution of code due to an input and it terminates the execution of the code abnormally. note : This type of errors are not logical or Syntax error. Types of Exception: 1. ZeroDivisionError , 2. IndexError , 3. TypeError 4. NameError ……. Exception Handling: Syntax : e.g. try : ------------ ------------ except: ------------ ---------- OUTPUT : 8 Index Out of Range try: lst =[1,3,7,8,9,50] print( lst [3 ]) print( lst [9]) except IndexError : print ("Index Out of Range")