Introduction – Text Input and Output – File Dialogs – Retrieving Data from the Web – Exception Handling - Raising Exceptions – Processing Exception using Exception Objects – Defining Custom Exception Classes.
Files – Definition A collection of data or information write into notepad and save those information called file . All the information stored in a computer must be in a file . File is a named location on disk to store related information. It is used to permanently store data in non-volatile memory (e.g. hard disk ), Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use files for future use of the data . ANGURAJU AP/CSE
There are different types of files, they are listed below: Data files Text files Program files Directory files, and so on. Different types of files store different types of information. ANGURAJU AP/CSE
1. Sequential access This type of file is to be accessed sequentially , Here we want to access the last record in a file you must read all the records sequentially . It takes more time for accessing the record. 2. Random access This type of file allows access to the specific data directly with out accessing its preceding data items. Here the data can be accessed and modified randomly. Types of file accessing
File Operations /Text input and output Whenever the user wants to read or write into a file we need to open it first , after read write process, then it needs to be closed, then only you avoid data losses. 1. Open the file 2. Read or write 3. Close the file ANGURAJU AP/CSE
File open function Python has a built-in function open() to open a file . This function returns a file object, so it is most commonly used with two arguments. Syntax: file_object = open(“filename ”, [“access mode”],[“buffering”]) Access mode – it determine the mode in which the file has to be opened Buffering – 0 , 1 if 0 no buffering if 1 line buffering is performed while accessing a file file_object - Once a file is opened and you have one file object ANGURAJU AP/CSE
Example file object name = open(“file name.txt”, “accessing Mode”) Example: f= open(“student.txt”, “w”)
With /as Statement The user can also work with file objects using the with statement. It is designed to provide much cleaner syntax and exceptions handling when you are working with code. Advantages : If any files opened will be closed automatically after you are done. To use the with statement to open a file: Syntax: with open(“filename” , “access mode”) as file: Ex : with open(“sam.txt” , “w”) as file: file.write (“ hai ”) ANGURAJU AP/CSE
File Opening M ethods MODES DESCRIPTION r Open the file for reading . The file pointer is placed at beginning of the file . w Open a file for writing only , overwrites the file if the file already exist, If the file does not exist , create a new file for writing rb Open the file for reading only in binary format . The file pointer is placed at the beginning of the file . wb Open a file for writing only binary files , overwrites the file if the file already exist, If the file does not exist , create a new file for writing ANGURAJU AP/CSE
r + Open the file for reading and writing . The file pointer is placed at beginning of the file . w+ Open a file for writing and reading , overwrites the file if the file already exist, If the file does not exist , create a new file for writing and reading a Opens the file for appending , The file pointer is placed at the end of the line . ab Opens the file for appending in binary format , The file pointer is placed at the end of the line . ANGURAJU AP/CSE
Reading and Writing Files The file object is used to access a file for reading and writing. There are two functions to do this operation read() write() ANGURAJU AP/CSE
Write a text file Write() method This method writes any string to an opened text file . The write() method does not add a newline to the character(‘\n’) to the end of the string Syntax: File _object . write(“string”) ANGURAJU AP/CSE
Example >>>f = open(“sample.txt”, “w+”) #open a file >>> f . write(“Problem solving python programming”) #write a file >>>print( f.read () ) # read a file >>> f.close () #close a file OUTPUT: Problem solving python programming ANGURAJU AP/CSE
Read the text file Read() method This method reads a string from the opened text file. The read method starts reading from the beginning of the file . The parameter is the number of bytes to be read from the opened file. Syntax: fileobject.read (count) ANGURAJU AP/CSE
readline () function whenever the user run the method, it will return a string of characters that contains a single line of information from the file file = open(“kk.txt”, “r”) print file.readline (): Output Hello World ANGURAJU AP/CSE
Example >>> f = open(“ sample.txt”,”r +”) >>> Str = f.read (10) >>> Print(“the value is “, str ) >>> f.close () OUTPUT: Problem py ANGURAJU AP/CSE
CLOSE THE TEXT FILE The close() method The close method closes the file object , after the completion of read write process. Python automatically closes a file when the reference object of a file reassigned to another file. It is good practice to use the close() method to close a file. Syntax: file _ object . close() ANGURAJU AP/CSE
Random access file /File Manipulation There are two major methods, Tell() Seek() Tell(): Tells you the current position within the file. file_object.tell () ANGURAJU AP/CSE
Seek() -this function read the string based on the offset and from where into a text file file_object.seek (offset , from where) offset – how many bytes to move (eliminate) from where – which position to move( 0 represent beginning of the file) Ex: file.seek (10,0) 10- move first 10 character 0 – from beginning of file file.seek (0,0) 0 – move 0 charater 0- read data from the beginning of file ANGURAJU AP/CSE
File Dialog Python Tkinter offer a set of dialogs that you can use when working with files. By using these you don’t have to design standard dialogs your self. Example dialogs include an open file dialog, a save file dialog and many others. Besides file dialogs there are other standard dialogs,
File dialogs help you open, save files or directories. This is the type of dialog you get when you click file,open . This dialog comes out of the module, there’s no need to write all the code manually.
Retrieving Data from the web: You can use the urlopen function to open a Uniform Resource Locator (URL) and read data from the Web. Using Python, you can write simple code to read data from a Web site. All you need to do is to open a URL by using the urlopen function, as follows: infile = urllib.request.urlopen ("http://www.yahoo.com") The urlopen function (defined in the urllib.request module) opens a URL resource like a file.
Example: import urllib.request infile = urllib.request. urlopen ("http://www.yahoo.com/index.html") print ( infile.read ().decode()) The data read from the URL using infile.read () is raw data in bytes. Invoking the decode() method converts the raw data to a string
Errors and Exceptions Errors: Errors or mistakes in a program are often referred to as bugs . This is made by the programmer . The process of finding and eliminating errors is called debugging . Errors can be classified into three major groups: a) Syntax errors b) Runtime errors c) Logical errors ANGURAJU AP/CSE
Syntax error: Python will find these kinds of errors when it tries to parse your program, Syntax errors are mistakes in the use of the Python language, and spelling or grammar mistakes in a keyword . Example: leaving out a symbol, such as a colon, comma or brackets misspelling a keyword incorrect indentation ….. etc ANGURAJU AP/CSE
Runtime errors If a program is syntactically correct that is, free of syntax errors it will be run by the Python interpreter. However , the program may exit unexpectedly during execution if it encounters a runtime error which was not detected when the program was parsed, but is only stop working when a particular line is executed. When a program comes to a halt because of a runtime error, problem Example: division by zero performing an operation on incompatible types ANGURAJU AP/CSE
Logical errors Logical errors are the most difficult to fix . They occur when the program runs without crashing, but produces an incorrect result . The error is caused by a mistake in the program’s logic . Example: using the wrong variable name indenting a block to the wrong level getting operator precedence wrong ANGURAJU AP/CSE
Handling Exception An exception is an event, which occurs during the execution of a program , that disrupts the normal flow of the program’s instructions An exception is a Python object that represents an error. When a Python script raises an exception , it must be handle immediately otherwise it terminates and quits. ANGURAJU AP/CSE
Python provides two important features to handle any unexpected error in the Python programs. There are two kinds of exception : Predefined exception predefined exception are build in exception ,it is also called as python object that handle the errors in the program. User defined exception : Assertions Try .. . Except ANGURAJU AP/CSE
ANGURAJU AP/CSE
ANGURAJU AP/CSE
Example: >>> 10 * (1/0) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 10 * (1/0) ZeroDivisionError : division by zero >>> 4 * a+3 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> 4 * a+3 NameError : name 'a' is not defined ANGURAJU AP/CSE
User defined exception A ssertions Assertions are carried out by the assert statement , An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program. Syntax assert Expression , [ Arguments] Example: assert (no>=0) , [ “ negative number”] ANGURAJU AP/CSE
Handling Exception( By using try except block) Here using Try Except block to write programs that handle selected exception. The try except statement: First the try execute the statement between the try and except keywords is executed. If no exception accurse, the except portion is skipped and execution of the try statement is finished. If an exception accurse during execution of the try portion, the entire statement in try block are skipped.
EXAMPLE: try: x= int (input(“Enter the number”)) except ValueError : print("That is not a valid number try again") Output: Enter the number “ram” That is not a valid number try again
Raising an Exception An exception is thrown by executing the raise statement. This will designates the problem. It can raise a exception using raise command: Sysntax : raise ValueError (“x cannot be negative”) This syntax raises a newly created instance of the ValueError class ANGURAJU AP/CSE
>>> raise KeyboardInterrupt Traceback (most recent call last): KeyboardInterrupt >>> raise MemoryError ("This is an argument") Traceback (most recent call last): MemoryError : This is an argument
try: a = int (input("Enter a positive integer: ")) if a <= 0: raise ValueError ("That is not a positive number!") except ValueError as ex: print(ex) Output: Enter a positive integer: -2 That is not a positive number!
Processing Exceptions Using Exception Object In Python possible to access the exception object in the except clause. Here we assign the exception object assigned to variable then it will be handled.
we can use the following syntax to assign the exception object to a variable. When the except clause catches the exception, the exception object is assigned to a new variable named as ex Now you can use the object in the exception handler. Syntax: try: <body of try block> except Exception Type as ex: < Handling exception statement>
Example: try: n= eval (input("Enter the number")) print("Entered number is",n ) except NameError as ex: print("Exception:", ex ) Output: Enter the number one Exception: name 'one' is not defined
Defining Custom Exception Creating Custom Exceptions In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.
In this to create a class named as CustomError is derived from the base class Exception By using the new class, now raise the exception using raise keyword.
Example: class LogError (Exception): pass c= int (input("Enter the number")) if(c>=0): print("the number is", c) else: raise LogError ("Enter only passitive number",)