Hi everyone, from this post today I’m going to talk about another important topic in Python. File, Directory handling and exceptions. First we’ll look at files and directories. As you all know files can be used to store data and directories are useful to store files. There are some built in function and methods useful in working with files and directories. Let’s see them with examples,
- First of all we want to open a file. It can be done using the open() method. The first parameter is the name of the file and the second parameter ‘r‘ for reading the file. If you want to open the file for write, then it’s ‘w‘. If you want to append data, then it’s ‘a‘.
- Now we have created a file object. Using the variable we can get few important details of the opened file such as name, mode, soft space and whether it’s opened or closed.
- When we are done working with the file, then we can close the file using the close() method.
- There is a built in method called read(), which can be used to read the content of the file.
- write() method will be used to write data to the file.
- If we have opened the file using ‘a‘, then we use the write() method to append data.
- There is another useful method, tell(), which will tell the current position of the cursor in the file.
- seek() method will help you to move the cursor within a file.
- To rename a file, we can use the rename() method, but before that we have to import the ‘os‘ module.
- To remove a file, remove() method will be useful. os module needed for this operation as well.
- Now let’s see how to make a directory.
- getcwd(), will return the current directory.
- chdir(), is used to change the directory.
- Finally, let’s see how to remove a directory using the rmdir() method.
Now you have a clear idea on how to work with files and directories. Now let’s see how to handle exceptions in Python. Exception is an error occurred in the execution of the program. This will lead to stop the program and get out with an error. So if we can handle these errors, then the program will run smoothly.
- ‘assert‘ is like the if-else statement. It will check for a condition. But it will produce the output with exiting the program.
assert (condition), <code to be executed if the condition is false>
- To prevent from exiting the program we have to use ‘try‘, ‘except‘ clauses.
- let’s see how to deal with the try except block..
<code to execute, if an exception occurs then it will move to the except>
<if an exception occurs>
<if no exceptions occurred in the try block>
- except part can be used with an argument as well. This will take a value which will describe the exception and can be used in the except part to give a more precious information for the user.
- There is another clause which can be used with the try. That is the ‘finally‘ clause. But this cannot be used with the except and else parts.
Hope now you have a clear idea about exception handling as well. See you soon with another important topic. Thank You!