In general, a file is a secondary storage device that is used for storing data permanently. Files can be in any format like txt, csv, xls, etc.File handling in Python involves the process of writing data into the file, reading data from the file, opening, closing and deleting the file. In this article, we will be discussing these processes in detail.
The concept of file handling is also available in other programming languages, but the implementation is either complicated or lengthy. Unlike other programming languages,file handling in Python is easy to implement. Also, whenever you want to analyse data, it is crucial to know how to read it from a given file. All these make the concept of file handling very important.
Python provides a set of built-in functions for opening, writing, reading, closing and deleting files. Let us begin with opening a file.
Consider you have a habit of storing all your passwords (credentials) in a text file. So you have created a text file on your desktop with the name 'PassCred'. Assume you need to add one more password to that file. Instead of doing this manually, let us see how to do this programmatically.
Before writing any data into the file, the file needs to be opened. This is like instructing the Python interpreter that the file with the specified name needs to be processed.
Python provides built-in function 'open()' to open any file for writing and reading. This function takes two arguments, one is the file name and the other is the mode (read mode, write mode) in which we need to open the file. Below is an example code to open the 'PassCred' file.
#opens the file named 'PassCred' f = open("PassCred.txt", "w")
Here, 'f' is the file object, using which we can write into or read from a file. Since we need to write one password into the file, we have specified the mode as 'w'. Some of the frequently used Python file modes are mentioned below.
This mode opens a file for writing
This mode opens a file for reading
This mode opens a file to append data at the end of the file
This mode opens a file to read and write
To write data into a file, we can use the built-in function 'write()'. This function takes the input data as an argument. Below is an example code to write a string into the 'PassCred' file.
= open("PassCred.txt", "w") f.write("FACE Prep") #writes 'FACE Prep' to the fle named 'PassCred'
Save the above code in a notepad file on your Desktop with the name 'main.py'. Execute it in the command prompt. After executing it, you can see that the input string "FACE Prep" gets written into the 'PassCred' file.
To write multiple lines, you can use the function 'writelines()' as shown below.
f = open("PassCred.txt", "w") lines = ['Learnn', 'Pythonn', 'FACE Prep'] f.writelines(lines) #writes multiple lines into the file named 'PassCred'
You can also check whether you have written correct data into the file by reading the data from the file. So next, let us read data from the file.
To read data from a file, we can use the built-in function 'read()'. This function does not take any arguments. Below is an example code to read data from the file 'PassCred'.
f = open("PassCred.txt", "r") print(f.read()) #reads entire data from the file
When you execute the above code in the command prompt, all the data written in the 'PassCred' file are displayed as the output.
By default, 'read()' function reads entire data written in the file. However, you can specify the number of characters to read. The below-given code prints only the first 4 characters from the file.
f = open("PassCred.txt", "r") print(f.read(4)) #prints the first 4 characters from the file
You can also read an entire line from the file using the function 'readline()' as shown below.
f = open("PassCred.txt", "r") print(f.readline()) #prints the first line of the file
To read the next line, you need to call the same function again as given in the below example.
f = open("PassCred.txt", "r") #prints the first two lines of the file print(f.readline()) print(f.readline())
Now that we are done with writing and reading. So, the next process is to close the file.
You can close a file using the built-in function 'close()'. This function does not take any arguments as shown in the below example code.
f = open("PassCred.txt") f.close() #closes the file name 'PassCred'
You can also check whether the file has been closed using the function 'closed()' as shown below.
f = open("PassCred.txt") f.close() print(f.closed) #prints 'True' if the file has been closedwithout any error
Python allows us to delete the file from your system using the built-in function. Let us see how?
Deleting a file is done using the function 'remove()'. remove() function takes a file name as an argument. This function is available in the built-in module 'os'. Below is code to delete the file 'PassCred'.
from os import * remove("PassCred.txt") #deletes the file named 'PassCred' permanently from your system
Note:If you delete any file using this function, the file will be deleted permanently, i.e., the file will be deleted from the Recycle bin.
1) what is file handling in Python?
File handling in Python involves the process of writing data into the file, reading data from the file, opening, closing and deleting the file.
2) How to append data into an already existing file?
To append any data in the existing file, you can use the mode a along with the file name when opening the file. The input data to be appended can be written using the function ‘write()’ as shown below.
f = open("first.txt", "a") f.write("Python") #appends 'Python' at the end of the file named 'PassCred'