Python File Handling & Exception Handling
Python File Handling
Till now, we were taking the input from the console and writing it back to the console to interact with the user.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile and can be accessed every time. Here, comes the need of file handling.
In this section of the tutorial, we will learn all about file handling in python including, creating a file, opening a file, closing a file, writing and appending the file, etc.
Opening a file
Python provides the open() function which accepts two arguments, file name and access mode in which the file is accessed. The function returns a file object which can be used to perform various operations like reading, writing, etc.
The syntax to use the open() function is given below.
The files can be accessed using various modes like read, write, or append. The following are the details about the access mode to open a file.
SN | Access mode | Description |
---|---|---|
1 | r | It opens the file to read-only. The file pointer exists at the beginning. The file is by default open in this mode if no access mode is passed. |
2 | rb | It opens the file to read only in binary format. The file pointer exists at the beginning of the file. |
3 | r+ | It opens the file to read and write both. The file pointer exists at the beginning of the file. |
4 | rb+ | It opens the file to read and write both in binary format. The file pointer exists at the beginning of the file. |
5 | w | It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file. |
6 | wb | It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file. |
7 | w+ | It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn't overwrite the previously written file. It creates a new file if no file exists. The file pointer exists at the beginning of the file. |
8 | wb+ | It opens the file to write and read both in binary format. The file pointer exists at the beginning of the file. |
9 | a | It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name. |
10 | ab | It opens the file in the append mode in binary format. The pointer exists at the end of the previously written file. It creates a new file in binary format if no file exists with the same name. |
11 | a+ | It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file if no file exists with the same name. |
12 | ab+ | It opens a file to append and read both in binary format. The file pointer remains at the end of the file. |
Example
Output:
<class '_io.TextIOWrapper'> file is opened successfully
The close() method
Once all the operations are done on the file, we must close it through our python script using the close() method. Any unwritten information gets destroyed once the close() method is called on a file object.
We can perform any operation on the file externally in the file system is the file is opened in python, hence it is good practice to close the file once all the operations are done.
The syntax to use the close() method is given below.
Consider the following example.
Example
Reading the file
To read a file using the python script, the python provides us the read() method. The read() method reads a string from the file. It can read the data in the text as well as binary format.
The syntax of the read() method is given below.
Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If the count is not specified, then it may read the content of the file until the end.
Consider the following example.
Example
Output:
<class 'str'> Hi, I am
Read Lines of the file
Python facilitates us to read the file line by line by using a function readline(). The readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.
Consider the following example which contains a function readline() that reads the first line of our file "file.txt" containing three lines.
Example
Output:
<class 'str'> Hi, I am the file and being used as
Looping through the file
By looping through the lines of the file, we can read the whole file.
Example
Output:
Hi, I am the file and being used as an example to read a file in python.
Writing the file
To write some text to a file, we need to open the file using the open method with one of the following access modes.
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file exists.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
Consider the following example.
Example 1
Now, we can see that the content of the file is modified.
File.txt:
Creating a new file
The new file can be created by using one of the following access modes with the function open(). x: it creates a new file with the specified name. It causes an error a file exists with the same name.
a: It creates a new file with the specified name if no such file exists. It appends the content to the file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.
Consider the following example.
Example
Output:
File created successfully
Removing the file
The os module provides us the remove() method which is used to remove the specified file. The syntax to use the remove() method is given below.
Example
Creating the new directory
The mkdir() method is used to create the directories in the current working directory. The syntax to create the new directory is given below.
Example
Writing python output to the files
In python, there are the requirements to write the output of a python script to a file.
The check_call() method of module subprocess is used to execute a python script and write the output of that script to a file.
The following example contains two python scripts. The script file1.py executes the script file.py and writes its output to the text file output.txt
file.py:
file.py:
Output:
50 -4 That temperature doesn't make sense! 212
The file related methods
The file object provides the following methods to manipulate the files on various operating systems.
SN | Method | Description |
---|---|---|
1 | file.close() | It closes the opened file. The file once closed, it can't be read or write any more. |
2 | File.fush() | It flushes the internal buffer. |
3 | File.fileno() | It returns the file descriptor used by the underlying implementation to request I/O from the OS. |
4 | File.isatty() | It returns true if the file is connected to a TTY device, otherwise returns false. |
5 | File.next() | It returns the next line from the file. |
6 | File.read([size]) | It reads the file for the specified size. |
7 | File.readline([size]) | It reads one line from the file and places the file pointer to the beginning of the new line. |
8 | File.readlines([sizehint]) | It returns a list containing all the lines of the file. It reads the file until the EOF occurs using readline() function. |
9 | File.seek(offset[,from) | It modifies the position of the file pointer to a specified offset with the specified reference. |
10 | File.tell() | It returns the current position of the file pointer within the file. |
11 | File.truncate([size]) | It truncates the file to the optional specified size. |
12 | File.write(str) | It writes the specified string to a file |
13 | File.writelines(seq) | It writes a sequence of the strings to a file. |
Python Exceptions
An exception can be defined as an abnormal condition in a program resulting in the disruption in the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code is not executed. Therefore, an exception is the error which python script is unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can be executed without any disruption. However, if we do not handle the exception, the interpreter doesn't execute all the code that exists after the that.
Common Exceptions
A list of common exceptions that can be thrown from a normal python program is given below.
- ZeroDivisionError: Occurs when a number is divided by zero.
- NameError: It occurs when a name is not found. It may be local or global.
- IndentationError: If incorrect indentation is given.
- IOError: It occurs when Input Output operation fails.
- EOFError: It occurs when the end of the file is reached, and yet operations are being performed.
Problem without handling exceptions
As we have already discussed, the exception is an abnormal condition that halts the execution of the program. Consider the following example.
Example
Output:
Enter a:10 Enter b:0 Traceback (most recent call last): File "exception-test.py", line 3, in <module> c = a/b; ZeroDivisionError: division by zero
Exception handling in python
If the python program contains suspicious code that may throw the exception, we must place that code in the try block. The try block must be followed with the except statement which contains a block of code that will be executed if there is some exception in the try block.
Syntax
Declaring multiple exceptions
The python allows us to declare the multiple exceptions with the except clause. Declaring multiple exceptions is useful in the cases where a try block throws multiple exceptions.
Syntax
Example
Output:
Arithmetic Exception
Comments
Post a Comment