Python File Handling
Python allows users to handle files, which basically means with the help of python you can open, perform operations like read or write and close files. Not only that, other useful things can also be done with files in Python.
Other languages require you to understand complex or long concepts in order to handle files but Like other concepts in Python, this concept is also simple and easy to grasp.
There is no need to import an external library or module to read and write files in Python. File handling can be performed with an inbuilt Python function
A file is a location in a non-volatile memory and they are used to store data permanently. Files are able to contain large amounts of data and on several occasions, while programming, you would need to deal with huge amounts of data. Therefore, it is an important topic to understand.
File handling should be performed in the following order:
- Open the file
- Perform the operation on the file – Read or Write
- Close the file
Now, you’re ready to understand File Handling in Python.
Python - Opening files
To perform various operations on a file, you need to open that file first. Python provides the open() function to read files.
This function takes three main arguments, file name, access mode, and encoding (optional). Upon executing the function, it returns a file object that can be used as a tool to perform handling tasks like writing, reading, etc.
The default encoding is utf-8 encoding, we will not the value of this argument for now.
Here are the different access modes in which the file can be opened.
- r – Read mode – Default value of the access mode argument. File will be opened in the read-only access mode. Returns an error if the file does not exist.
- w – Write mode – File is opened in the write only mode. If the file does not exist, it will create a new file.
- a – Append mode – This access mode opens the file for the operation of appending at the end of the file. Similar to the write mode, it will create a new file if the file does not exist.
- x – Create Mode – This mode creates a new file. However, if the file already exists, our function will return an error.
By combining ‘b’, ‘+’, or ‘t’ with the access modes described above, you can specify some extra detail to open the file. Here’s how it can be done:
- rb – This will open the file in the read-only mode in the binary format.
- wb – This will open the file in the write-only mode in the binary format.
- ab – This will open the file in the append mode in the binary format.
- r+ – Opens the file for the operation of both reading and writing.
- w+ – Opens the file for the operation of both writing and reading.
- a+ – Opens the file for the operation of both appending and reading.
- rb+ – This opens the file in both read and write mode in binary format.
- wb+ – This opens the file in both write and read mode in binary format.
- ab+ – This opens the file in both append and read mode in binary format.
- rt – Opens the file in read-only mode in text format.
Python - Reading files
We know the access modes to open files, now let’s see how to open files to read them.
Example
You can also read a limited amount of data from the opened file in this way.
Example
Let’s understand the code:
- The value in the brackets specifies the number of data values we want to read.
- Data collected from the read() function can be stored as a string in a variable. And therefore, it can be printed normally like a string too.
Python - Writing files
Writing into a file is also super easy, here’s how it can be done.
Example
Let’s understand the code:
- We told Python to write a file named “example1.txt”, if such a file does not exist, Python will create a new file, and then write into it.
Bonus Tips
- If you are working in the text format of the file, it is recommended to specify the encoding for the file operations. Depending on the platform, our code might behave in different ways if we keep the encoding type default.
- From now, we will specify the encoding as utf-8 encoding.
2. We create another file object with the same name to read the file.
Python - Appending Files
You can append new information to the already existing file with the append access mode.
Example
Now, after understanding reading and writing files, we should move to the equally important of the file handling, i.e., closing a file.
Python - Closing Files
You are needed to close the file after performing the operations. When you close the opened file, it frees up the resources associated with that file.
Python has the capability to close the unused files automatically using the inbuilt garbage collector but you must never be dependent on Python to close the file.
To close the opened files, Python provides the close() method.
Example
We used the try-finally block to close the file to make sure the file does not stay open in the case of an error.
Python - Deleting Files
The OS module is required to remove a file. This module contains the method remove () that takes the name of the file as an argument.
Here’s an example:
Example
The error when we try to open the file is the proof that the file was deleted successfully. Python will return an error if the file that we wanted to delete doesn’t exist.