Python File handling a method to store the output of the program to a file or take input from the file. File handling is a key concept in the programming world. File handling used in almost every kind of project. For example, you are creating an Inventory management system. In the inventory management system, you have data related to sales and purchases so you need to store that data somewhere. Using Python file handling you can store that data into the file. If you are trying to perform some analysis on the data then you must be provided with data in the form comma separated file or Microsoft Excel file. Using file handling you can read data from that file and also store output back into that file.
While using file handling there are different types of modes available. Just have a look at them we will explain them in detail.
- “ r “, for reading.
- “ w “, for writing.
- “ a “, for appending.
- “ r+ “, for both reading and writing
Let’s take a look at how to create a file using Python programming language.
Take a look at the left side we have only hello.py file.
Now let’s execute the code.
f = open("data.txt","w+")
w+ stands for: Open a file for writing and reading.
The file with name data.txt has been created.
Open and write into file
We will be using the above-created file. Let’s write some data into the file using code.
f = open("data.txt","w+") for i in range(5): f.write("line " + str(i) + "\n")
The file looks like this
Append into file
“Write” option erases all the previous data present in the file. For appending data into an existing file we need to use a mode of “a”.
Let’s take a look at the code.
f = open("data.txt","a") for i in range(2): f.write("appended lines " + str(i) + "\n")
The data.txt file will look like this
Read data from file
Let’s take a look at code to read data from the data.txt file.
f.read function output all the data present in the file.
f = open("data.txt","r") print(f.read())
If we need to read the data line by line we use readline() function.
For reading first two lines.