Day- 12 Python +SQL FREE Sessions | File handling in Python - Part-2

Learn Python file handling with the `with` statement for reading, writing, and appending files, plus binary mode for images. The session covers exception handling with `try`/`except` blocks, `else` and `finally` clauses, and the `raise` statement to prevent crashes and build reliable programs.
Chapters
Hello everyone, how are you all? Hi, good evening, ma'am. Yeah, good evening.
How are you? I'm good, thanks for asking.
Okay, is my screen visible to everyone?
Yeah, is it okay? So let's get started.
So in the last session, which was yesterday, we discussed about file handling, what exactly file handling is and how to work on any file, how to open it, how to close it, and the basic operation read we have performed. Now in this session also we will be talking about file handling. Okay, so this is new.txt which we have already created in the last last session we tried to append some lines in that file. Now I'm going to read the same file using the with method. With with method you can simply— you need not to basically close it with with if you are going to do it.
So as we have already discussed the with statement which is over here, I'm going to take the same one and I will just start it up over here. I'm going to use F6, and let's say for a in F6, print a.
So here with this one, we are opening the file and we are reading each and every character from that particular file. So I'm not using any other inbuilt method to read it, I'm just using for loop to make it iterate over the characters and print it. Now let's say I'm going to say a.strip. So this will give you the— yeah, this will also give you the entire data but without extra spaces and all. White spaces will be removed basically. Okay, with with method, if you wanted to write on your file or you wanted to append some content in your file, then you have to follow the method that you have to open your file like this, and then you can say that like f6.write, and over here you have to make sure you're opening it within the write mode.
New content added.
Now you can see our file content has been updated. Earlier there was something related to Python, but now I have just added this one. The reason we have, we have lost the previous content is because we are opening the file within the write mode. When you open the file within the write mode, it means you wanted to truncate the current data. Truncate means remove the current data. When you wanted to remove current data and you wanted to add the new one, it means after erasing, after removing all the content, we are going to basically overwrite on the same file. Then this is how you have to do it. You just have to open it within the w mode and then apply the write function. Now let's say you don't want to remove it but you wanted to add it. Then in terms— then when you wanted to add something, then you have to open the file Let's say I'm going to say 7, and I'm going to open it within append mode because I wanted to add it.
Let's see this. It should be F7.
Okay, so now you can see I have tried to open the file within the append mode. I'm trying to add a new line in it. Now we will check it with this for loop which we already have. You can see I have 2 lines added.
Do anyone have any question in this? Yes, anyone, any question?
So when you're applying with the a mode and you are going to append the data, then your previous data will also be there in your file.
Okay.
If you are using with mode, then you need not to close your file because with statement will automatically close your file. Now let's say I want to copy the content of one file to another file, then how to do that? So simply you have to follow with method. I'm going to use the with method because in with method the files will be automatically closed. So I'm going to use new.txt and then I will create, let's say, destination.txt as a new file after copying the content of one file into another file. Okay, so you have to type with and then you will write open and then the file name comma the mode that you are opening in and then as, let's say, whatever variable like F6, F7 that I am giving, you have to write that. Then again you have to open one file within the write mode as a dest— as a destination file, and then for loop for writing over in the new file. Okay, so this way you can simply append the data from one file to another file. So I'm writing new.txt because this is our initial first file, and then I have the second file which is destination.txt, which I am opening in the write mode. And as you can see on my left-hand side, the file has been created and the same data has been added in this file as well. Any question in this?
Yeah, anyone, any question? No, ma'am.
Okay, so that's how you can copy from one file to another file. But there are some certain types of errors that you might encounter while coding. So there are some methods to handle those errors as well. So one of the famous ones which is in Python is try and except block. So try and except block can help you handle errors. So that is called error handling or exception handling. Okay, so in case you are encountering any of the error, like while doing copy, like copying content from one file to another, trying to append it, then there are possibilities that you will encounter errors. So don't worry, the next concept that we are going to cover is the exceptional handling or error handling. So then we will cover how you have to handle those errors. Up till now we have worked on these txt files, right? new.txt, destination.txt, and this is related to text files. As I told you in the beginning that you can work on two types of files. First is the text, text file, and second is the binary file. Binary files are like images and, uh, let's say images and videos, right? So now we will see how we have to basically work with the images. So I'm just going to take one image and I will add it up in the same folder.
Okay, let me just cut it and paste it in this folder.
You can take any image from Google for just for trial, just like I have taken.
So let me just rename it.
Okay, so you can see on my left-hand side I have an image, imagecard.jpg. This is an image. Now I'm going to make it read using the file handling. So now in this case you have to use the methods with the binary modes. When you wanted to add binary mode in it, then you have to use B with it. So simply I'm going to use with method. So with open and then image_card.jpg and then RB as a file and then binary data I'm going to read. So if your file is in the JPG or PNG or JP— JPEG, then accordingly you have to mention it. So this is the binary data of the image that I have added. You want to be able to view the exact image that you have, like the image which I have is this, but you won't be able to view the exact one because we are opening it in the— in terms of computer. So this binary data is going to give you the data something like this, which consists of 0 and the HFX codes and all. Any question, anyone, in this? No, ma'am. Is this clear to everyone? Others? If I'm going to show you that the type of this binary data is—
let me just type it over here.
This is in bytes. B means we are getting the byte objective, and you can see everywhere it is /x notation. So /x notation means this is hexadecimal byte value. Whenever you are reading non-text files like audio, video, images that doesn't have any text, then These type of binary data, these type of binary representation or byte objects will be generated for you in the output. Okay, now let's talk about the next concept, which is exception handling, or you can call it error handling as well. So there are multiple types of errors that will be there when you are just trying to code, or maybe some errors are related to the syntax and many more. So there are ways also to handle those errors. When it comes to the ways to handle the errors, is like, let's talk about first errors, like which all type of errors you might encounter in your coding journey. The number one, which is very basic, is the syntax error. This is basically— you will encounter this error whenever you have made any syntax error. Maybe you have misspelled any keyword, or you have missed any colon, or you have some unbalanced parenthesis, or maybe you have opened one but you haven't closed it. So at that time, you will encounter syntax error. Second type of error is the type error. In case of type error, this type error is a Uh, like it will occur whenever you are writing something wrong type, like, like string to integer you are trying to do. It means which related to the data type, if you are doing it unbalancedly, unbalanced way, then you will get the TypeError. Then comes the next one which is again very common, which is NameError. So in case of NameError, NameError is raised when you have When that particular name is not defined anywhere in your Python, in Python, and anywhere in your Python notebook, then at that time you will encounter name error, type error, name error, and syntax error. Now these are all the type of errors that you will encounter: tab error, type error, index error, value error, buffer error, EOF error, import error, lockup error, memory error, system error, runtime error, timeout error. So these are the type of errors that you might encounter in your coding journey: zero division error, unbound local error, not a directory error. So all these types of errors will be there. Now let's talk about how to handle them. So common type of error are easy to handle, and that makes sense too. Like if you haven't closed parenthesis, then obviously you should get error. But to make your platforms, to make your applications, or to make your analysis user-friendly, or make it, uh, understandable by the non-tech team, then at that— in that case, you have to do error handling or exceptional handling. So there is one common one which is try and except block. So try and except block syntax is like you will write try Sorry, try, then you will write whatever your statements are, whatever you wanted to include, just type it. And then except, after you're writing except, you have to mention the error, which error you want it to accept, and what do you want it to print. So if you are, let's say, if I'm going to This way, I'm just going to remove this and I'm going to— you can see I'm getting syntax error saying that Unicode error. This is specifically syntax but related to a Unicode error. So now in this case, this seems so like people used to get afraid of, okay, I'm getting an error, now how do I have to proceed? But if I am the one, I'm creating a platform, I'm creating, I'm developing something, then at that time what I can do is I can simplify this for the user. What I can say is I can simply mention what exactly the resolution of this is, what, what is exactly the solution basically. So whatever you want, whatever you think that could be the solution of this error, then you have to write it within print statement making it user-friendly. For an example, let's talk about the very basic one. Let's say I have two variables. One is A, another one is B. In B I am going to store, let's say, Python, and in A I'm going to store 2.5. So we know that 2.5 is the float value and Python is a string value, and we cannot add these two. So if I'm going to directly say print A plus B, I will encounter an error which is TypeError, which says that unsupported operand types for plus, which is float and string, cannot be added. Now I'm going to write— rewrite the same code with the error handling to make it user-friendly. So you can say try, and I'm saying try print—
sorry, let's say d is equal to a plus b.
Okay, so within the try block you have to type something which is which might create error or which might raise an error. And within the except block, you have to mention the type of error that you might encounter in this. So which is TypeError. Now I'm going to make it user-friendly by adding a print statement saying that error Numbers and strings cannot be added together. Or you can say that kindly make a valid operation, and you can run this. Now in both— this is the first case which we did earlier, and this is the second one. Now this is with the red color highlighting that, okay, you have made a mistake. But this is very simple one which is just giving a solution to us. Okay, there is an error that numbers and strings cannot be added together. Kindly make a valid operation. So now within this you have to— now we got it that, okay, float cannot be added with a string. So either we can— we have to remove string, or either we have to remove float. Any of the data type we have to choose, and then accordingly we can perform. Any question in this?
Yeah, any question in this? No, ma'am.
Okay, now let's say I have a list.
List is equal to Let's say list1 is equal to 8, 9, 5, 6. Okay, and I'm going to print list1. From list1, I want 5th element.
So as you can see, I have written 5, but in my list only I have is 4 values, 4 values. And again, the values indexes will start from 0. So 0, 1, 2, 3, it means I just have 4 index values. 0, 1, 2, and 3. I just have these 4 values. When I have just these 4 values and I'm trying to print something which is out of index, it means that index doesn't exist in that particular data type, then at that time you will get this IndexError. Now to handle this IndexError, you can simply use the try and except block. So I'm just going to rewrite it.
Try, accept. Error occurred.
Or let's say The index value doesn't exist. You can see now we have resolved index error. Now we are handling basically in the user-friendly way, and we are generating a simple— we are using a simple print statement to display an error. If let's suppose there I have— I'm adding one more print statement, and within this print statement I am just going to write something which is valid. So let's say 2. So 0, 1, 2. So we are expecting 5 to be printed. So if I am going to run this, then what— whatever you are going to write within try, right, if that is not generating an error, then you will get the output. But if it is generating an error, then that particular thing will be passed to except, and the except block will give you the output. Did you get it?
Yeah.
Now let's say you are not sure whether you will get 1 error, 2 error, 3 error, or more than that. Then that time what you have to do is you have to continue adding the except blocks in this. So there are higher chances that if you are writing a complete program, then adding a try and except block is a good choice. But when you are adding a try and except block, try to add more except block to make it more user-friendly.
So you can say this, and you can continue writing your print statement, and you have to write— let's say I'm just writing something, okay?
So over here you have to mention which type of error do I have to handle, okay? This except block will handle the IndexError, okay? And this one will handle Type error. Earlier we were getting type error.
Yeah, this one.
So I'm just going to take this and add it up over here.
Okay, and this too I will take. And I will add it up over here.
So this is going to generate an index error and this is going to generate a type error.
Now I will just try to execute.
The index value doesn't exist because whenever Python code executes, right, whenever we are trying to run the Python code, there is— I, I, we discussed this in the session number 1 that Python is an interpreted language. This is not a compiler. So compiler takes the entire code but interpreters takes the code line by line. Therefore, whenever you have more errors, or whenever you have, uh, let's say if you have error in this line and this line also, so first this error will be—
will ask—
like, first you have to handle this error. Once this error is handled, then only you will get a chance to correct it using the kernel. If you know yourself, then you can correct it. But in case of Python, Python is interpreted, means line by line your execution will be done. So first is we are trying to store something, it will store it. We are trying to store something, it will store it. And again, but then comes the try one, then it will take, okay, you have to try this, this is working fine, display the output. If let's say, let's move on to the second one, which is this one, this is generating an error, so it will be passed. This particular statement will be skipped this time. And this will be passed to an except block and will check, okay, is it generating IndexError? If it is generating IndexError, it will be like this particular print statement will be printed. But if this is not generating IndexError but this is generating a TypeError, then it will be passed to the second except block and then this will be printed. But this particular d statement will be neglected. Did you get it now?
Yeah, is this clear to everyone? Yeah, ma'am. If you want this output, then you simply can comment it and you can see that you will get error.
So this goes line by line. So this is try-except block. The second one which we have for error handling is try-except-else. So try with else, you can use else block also in this. And after that we also have finally.
So simple, just go write else. Print display every time when no ex occurs.
So when no errors will occur, it means like this try block is not having even the IndexError or the TypeError, then this else block will be printed. And if you want a statement to just display every time, then go with the finally. So you can see this statement is not getting printed because we have error. When you have the error, then else will be neglected. Else will be only executed when there is no exception. For example, let's say I'm going to comment this line also. Then the else statement will be printed. Otherwise, this else statement will be skipped and will be passed to the next one, which is finally. Finally is whenever you want something to be executed, always executed, whether it is related to try, except, finally, or else. Every time you want something to be printed, then go with the finally. This shows— this is basically added just for the testing purpose that everything has been executed successfully. Out of this try and except block.
Got it?
You got it. There is one more exception that you can add. Just like in functions, we have return statements, right? Whenever we want to return some values, we go with the return. But now let's say you yourself wanted to force a specific exception, you wanted to raise an error. When you wanted to raise an error, then simply write raise, okay? For example, let's say I wanted to generate NameError. Okay, I want to generate NameError, TypeError, IndexError, any error it could be. But let's go with the NameError, which is very basic. So NameError means wrong name. If you are printing, if you are trying to display, then go— then you have to do that, right?
And so let's try raise name_error, hello learners, except, let's say, name_error, print error.
Now you can see I'm, I'm raising a name error, which is hello learner. You get it? And here also you are getting error. This way you can raise any type of error. Let's say you wanted to generate IndexError, then just type index and this will generate IndexError.
Okay, simply just remove this, add index, and this will generate IndexError. You can see I've written the wrong spelling. I should be in caps.
Yeah, so now you can see, you— this is how you can generate or you can create this error. So in this case, what we are doing is we are using try block, and within the try block we have written that may raise an error. Okay, the statement that we have written, raise NameError, means that we are creating a custom message along with the NameError. Like in the format of NameError, I'm writing the custom message as well. Whatever message you want, suppose unsupported or something you want, then this will generate index unsupported. So this is just a custom message. You can modify whatever you wanted to write. Then within except, except block where I have written name error, then in the except block name error will be caught. Like wherever the name error is, name error exception will be caught and raised to the try block. And then we are printing error just to, uh, just a simple message to be displayed. And then we have the raise. First error is raised and handled by the except block, but then again I have written raise which is again going to raise the same error.
Got it.
So this is called exceptional handling or error handling. This is important because when we are creating a long, lengthy programs, or we are creating GUI applications, or when we are creating AI tools or something, then we have to use these methods. Now, what do you think, why should we use this? Yes, anyone who have understood it, like what exactly we have been discussing? You don't have to run the code again or start the procedure again. Yes. So basically, whenever you wanted to prevent your program from crashing or producing incorrect results, then at that time, in that case, you have to use the exceptional handling because this is going to improve your program reliability. Okay, so like right now we are going code cell by code cell by code cell, right? But when you are going to create this .py file, so everything will be executed at once. And if there is an error anywhere in your file, then your execution will stop there itself. So to, to prevent your program from stopping or crashing, then you have to use this. Okay, and this is also going to simplify your errors. And if you are going to use it, you will have a clear understanding of the error and you will have a good understanding of the logics as well, that when to use it, which type of error will be used, will be raised, and when. Then this is the good way to improve all those things.
Okay.
All right, then your today's task is to practice this file handling, and then we'll discuss the next concept in the next session. Which is tomorrow, same timing. The next concept is we will be discussing some modules and libraries from Python. There are multiple modules and we will see how we can use them, how we have to import those libraries, and which all type of libraries are there for making our task easy.
Okay. All right everyone, bye-bye, take care. Thank you, ma'am. Welcome, thank you, bye-bye.










