FILE HANDLING IN PYTHON
In this article, we will learn about File Handling in python. We will learn about open, read, write, append and delete file methods that we must know as a python programmer.
File in Python
We all know about what is a file in conventional terms but let’s talk about the file in python. It is just like a normal file that is stored in the conventional way inside the hard disk because things stored in RAM are temporary and are likely to be missing once the computer gets turn off.
Let’s say we want to read from or write a file in python so we will have to open the file first. And after performing particular task we need to close the file as well. So, we have to follow all the steps in order to handle files in python. Python file operations is divided into four parts:
- Opening the file
- Reading the file
- Writing the file
- Deleting the file
Opening the File
In order to open a file in Python, we will use the
open() built-in function. This function will return python the file object. The open() function will have two parameters: filename and mode
The open() function takes two parameters; filename, and mode separated by the commas (filename, mode)
- Filename is going to be the name of the file that you want to open.
- Mode is going to decide that in which specification we want to open the file. There are four different types of modes that you can use:
"r"– Read Mode – It is the default value when there is no mode defined. ‘r’ is used to open the file in read mode
"a"– Append Mode – It opens to file for appending, and if there is none then it creates one.
"w"– Write Mode – It opens the file for writing, This mode can overwrite or create new content in the file.
"x"– Create Mode – It is only validated as long as there is no existing file. If the file already exists in the directory, then it shows an error.
"t"– Text Mode – Default text view mode. The file in python always opens in the text mode unless you change it.
"b"– BinaryMode – If your file is an image then you may want to utilize this mode to open image files.
To open the file, you need to use the following syntax in a python file, let’s suppose that file is main.py, here you will enter the following:
f = open("new.txt")
Note: The above statement opens the file named ‘new’ in the default read (‘r’) and text mode (t’). If the file doesn’t exist in the directory, then you will get an error.
Reading the File
Now let’s assume that we have a file named ‘new.txt’ in the same folder where our main.py file is, once we have opened the file and returned it then we will start reading the contents of the file in python so for that we will use the read() method:
f = open("new.txt") print(f.read())
Once the read() method is printed then all the contents present in the ‘new.txt’ file will get printed on the screen, so the output will be:
Hello, I love Python Programming I am learning Python Wish me best of luck
Reading Parts of File
You can read parts of the characters present in your ‘new.txt’ file too if you want, let’s say that you want to read the first 10 characters present in your file then you can use the method read(), here you can see that you have specified 10 as a number to be read only. For Example:
f = open("new.txt") print(f.read(10))
Output will be:
Hello, I l
Reading Lines of File
You can start reading the lines too, let’s say that you have more than one lines in your file, then you can read one line at a time. For Example:
f = open("new.txt") print(f.readline())
Hello, I love Python Programming
If you run the readline() function twice then python will execute the second line and on.
f = open("new.txt") print(f.readline()) print(f.readline())
Hello, I love Python Programming I am learning Python
Closing the File
Another important thing to remember is to use the close() method to close the files. Sometimes the file that we read on python still goes on buffering in the background, so we need to make sure that we close the file in order to save disk space and processing errors.
f = open("new.txt") print(f.readline()) f.close()
Writing to a File
Once we learned about reading the file, now it is time use the write() method in
'w' mode. This will erase all previous content and overwrite new one. For Example:
f = open("new.txt", 'w') f.write("Where did the text go?") f.close() f = open('new.txt') print(f.read())
Where did the text go?
So, the new text has replaced the old one, and all previous data is erased.
Creating a New File
Let’s assume that you don’t have a text file in your directory to open but you still can create a new file in python by sing
'x' parameter, store data in it and read from it later on. For Example:
f = open("new_word.txt", 'x')
Run the code once, in order to write something to it, remove the previous code and enter the following:
f = open("new_word.txt", "w") f.write("I have created a new file named new_word.txt") f.close() f = open("new_word.txt") print(f.read())
I have created a new file named new_word.txt
Appending To A File
You can append text at the end of the existing content as well by using the
'a' as your parameter. For Example:
f = open("new_word.txt", "a") f.write("\nI have appended some text in new_word.txt") f.close() f = open("new_word.txt") print(f.read())
Output will be:
I have created a new file named new_word.txt I have appended some text in new_word.txt
Deleting a File
You can delete a file in python as well by using the import os statement
import os os.remove("new.txt")
If you will check your directory, you will see that the ‘new’ file isn’t there anymore.
For references, click here