File Handling is an important aspect of the Python Programming language as it is used in web applications. We can create files, read files, write in files, can update files, and can also delete files.
A file can be handled in two ways i.e. Binary(b) and Text(t). A file in Python is also saved with the extension of .txt.
So the first function of file handling is open() and this function will return a file object. There is one important point that you also have to close a file once opened. A file is opened using f.open() and closed using f.close() . This open() function takes two parameters:-
There are a total of 4 members to open a file in python:-
"r" = Read - Opens a file for reading.
"w" = Write - Opens a file for Writing.
"a" = Append - Opens a file for Appending.
"r+" = Read and Write - Opens a file for Reading and Writing.
The syntax for opening a file:-
Opening a file in reading mode:
The above-given syntax is for opening files in reading mode and also the file will be opened in text mode as a file is opened by default in the same mode.
Reading a file on a server
Let's consider a file named file1.txt saved in the same folder as python
To read the above file we will use open() to open the file and read() to read the file.
To read lines in python files we use a function known as readlines() but it will read only a single line.
If you want to read more lines then you have to add more readline() functions. For eg- if you want to read 3 lines then you have to use the readline() function thrice.
Writing in a File
"a" = will append at the end of the line
"w" = will overwrite the content
Append the content
Now we will take an example where we will append the file:-
As you can see that the data has been added at the end of file1.
Now the data from file1 has been removed and the date of file1 has been updated.
Delete a File
In python, you can delete a file using the remove command. Now we will remove the file named file1.txt every python file is removed using import of os module.
Each file in python contains a directory. The os module in python helps in creating, removing, and changing directories.
Syntax of Python Directories:-
Now we will create a test directory in a current directory:-
To change a current directory we use chdir() method. Generally, it takes an argument, which is the name of the directory which we want as our current directory.
To delete a directory we use the rmdir() method which is passed as an argument in the method
Exception in Python
In the Python programming language, when a script encounters a situation which it cannot cope up with, then it raises an exception. An exception is a Python object which represents an error in the program. There are several exception methods in python:-
Exception - Used for all exceptions
StopIteration - Occurs when the next() method does not point to any object
StandardError - Base class for all built-in exceptions
ZeroDivisionError - Raised when division or modulo by zero takes place for all numeric types.
FloatingPointError - Raised when any floating-point calculation fails
KeyError - Raised when a specific key is not found in the directory
SyntaxError - Raised when there is an error in syntax
IndentationError - Raised when indentation is not done properly
ValueError - Raised when arguments contain invalid values
RuntimeError - Raised when a generated error does not fall into any category.
There are several more errors in Python.
To handle exceptions in python we use try: except. If you found something suspicious in your code which may raise an exception then you can defend your program by placing the suspicious code in a try: block. After that add an except statement, followed by a block of code that will handle the problem easily.
The syntax for Try Except:-
Python is a language that allows you to create your exceptions by deriving some classes from the built-in exceptions. Now we will create an exception using Runtime Error. This is very useful when we need to display more accurate information when an exception is caught.
In the try block, the user-defined exception is raised and after that, it is caught in the except block. The variable e is used to create an instance of the class Network error.
I hope that you had easily understood the concept of files in python. You can visit my youtube channel for more help regarding this topic.
Thanks for reading. Hope you liked it. Many more to come in the future.
Note:- The amazing article used in this post is designed by Victor Korchuk