
In this post, we are going to learn about File Handling in Python i.e. different file handling methods like opening and closing files, appending the contents of the file, writing, reading files, etc in detail along with suitable examples.
Why learn File Handling in Python?
- Each and every language provides file handling, but the implementation is much more complex and difficult to understand and that’s where Python comes into picture. Python ships with many easy to use built-in modules and functions for handling files.
- Another plus side of learning File Handling in Python is that you don’t need to install any external library to process your files.
What is file?
Computer files are used to store data in digital formats such as plain text, large databases, and other content. All programs need input and output in order to process or display the data and for all these purposes files are required. Computer files can be organized in various directories. These directories in turn store files. In order to save the data in the files, they are stored in ROM (a memory that does not erases data as the machine is turned off). Whenever we need to read the content of the file, at first, we need to open it and then we process the required operations and then close it. So, now let us dive deeper into different operation modes.
Different File Handling Operations:
- Opening file
- Reading contents from file
- Writing to the file
- Closing the file
Opening Files using Python
Whenever we want to access the contents of any file, at first we need to open the file.
Function used: open()
Usage: This function is used to open the file that is present with the name specified in 1st parameter
Syntax: open(“filename”, ”mode”)
Parameters:
- open() function takes 2 parameters.
- 1st parameter takes the name of the file or path of the file that we want to open.
- mode specifies the mode in which we want to open the file like read, write, append etc.
Example1:
f = open(“copyassignments.txt”,”r”)
Here f is declared as a variable to open file
copyassignments.txt is the name of the file
r is the read mode i.e. we want to read the file
Example2:
f = open(“C:/User/Py/copyassignments.txt”,”r”)
Here f is declared as a variable to open file
C:/User/Py/copyassignments.txt is the path of the file that we want to open.
r is the read mode i.e. we want to read the file
Different Modes of Opening File:
w | This mode opens the specified file for writing data to the file. If the file doesn’t exist then it creates a new file. If the file contains some content then it will be overridden. |
r | This is the default mode and it is used to read the contents of the file. |
x | This mode is specified when we want to create a new file. If the file with the same name exists then an error is delivered. |
a | In this mode, the file is opened for appending purposes (adding more content to the file). It doesn’t override the data that exists in the file. If the file doesn’t exist then it creates a file. |
t | This mode exclusively opens the file in text format |
b | Whenever we want to open the file in binary mode then “b” is used. |
+ | This mode is used when we want to read as well as write to the file |
Note: r and t are the default modes.
That means,
f = open(“copyassignments.txt”) is equivalent to f = open(“copyassignments.txt”,”rt”)
Reading Files in Python
- Methods used: read(), readlines()
- Usage: These method are used to read the data of the files
read() | This method is used to read the contents of the whole file. By default, it reads the whole content. We can also specify a particular number of characters that we want this method to return. |
readline() | This method is used to read the contents of the file in line by line manner. |
readlines() | This method is used whenever we want to read all the contents of the file line by line. It will return the whole content of the file in list format. |
1. read()
f = open(“copyassignments.txt”,”r”)
print(f.read())
Explanation:
The above code will first open the file “copyassignments.txt” in reading mode.
The second line print(f.read()) will actually print all the content that is there in the file
f = open(“copyassignments.txt”,”r”)
print(f.read(15))
Explanation:
The above code will first open the file “copyassignments.txt” in reading mode.
The second line print(f.read(15)) will actually print the first 15 characters of the content that is present in the file
2. readline()
f = open(“copyassignments.txt”,”r”)
print(f.readline())
Explanation:
The above code will first open the file “copyassignments.txt” in reading mode.
The second line print(f.readline()) will actually print the first line of the file.
f = open(“copyassignments.txt”,”r”) print(f.readline()) print(f.readline())
Explanation:
The above code will first open the file “copyassignments.txt” in reading mode.
The second line print(f.readline()) will print the first line of the file.
The third line print(f.readline()) will print the second line of the file.
Writing to the file in python
Whenever we want to write or add content to the existing file, we need to open the file in write or append mode (“w” or ”a”)
- Method used: write()
- Usage: write() method is used to write contents to the file. The specified data can be added in two ways either by writing or appending
Let us understand with an example
f = open(“copyassignments.txt”,”w”)
write(“We are here to help you for your assignments”)
Explanation:
The above code will first open the file “copyassignments.txt” in write mode.
The second line “We are here to help you for your assignments” will be added to the file. And if the file already has some content then it will be overridden.
f = open(“copyassignments.txt”,”a”)
write(“This will be added at the end of the file”)
Explanation:
The above code will first open the file “copyassignments.txt” in append mode.
The second line “This will be added at the end of the file” will be added at the end of the file. Append mode do not override the data that is already present in the file
Closing the file in Python
Every time a file is opened, it needs to be closed. And for this purpose close() method is used. This is the most important method in file handling.
Closing a file after the operations are performed is a good habit. This will prevent someone from performing unwanted operations on file and prevent data manipulation.
- Method used: close()
f = open(“copyassignments.txt”,”a+”) write(“We are the Python pioneers”) f.close()
Explanation:
The above code will first open the file “copyassignments.txt” in append and read mode.
The second line writes (“We are the Python pioneers”) will be added at the end of the file.
The third line f.close() will close the file.
Other Advanced Most Usable File Handling Methods:
seek() | This method is very useful when we want to change the position of the file cursor. |
seekable() | seekable is used when we want to check whether the file cursor can be changed or not |
tell() | This method is used to know the current position of the file cursor. |
Thank you for reading the article, please visit our homepage to learn more about python.
Also Read:
- Filter List in Python | 10 methods
- Top 25 Pattern Programs in C++
- Currency Converter in C++
- SQLite | CRUD Operations in Python
- Number Guessing Game in C++
- Image background remover in Python
- C++ Project Structure
- Python | Check if a string is a palindrome or not without Recursion
- Python | Check if a number is an Armstrong Number or not using Recursion
- Python | Check if a number is an Armstrong Number or not without using Recursion
- Python | Shuffle a list using recursion
- Python | Shuffle a list without recursion
- Python | Implementing switch case using functions
- Python function to check whether a number is perfect or not
- Python | Find LCM using function
- Python | Find HCF using function
- Python | Convert the binary number to decimal without using library function
- Python | Create a basic operations calculator(+, -, /, and x), create a separate function for each operation
- Python | Detecting the number of local variables declared in a function
- Python | Making a chain of function decorators (bold italic underline etc)
- Python | Access function inside a function
- Event Management System Project in Python
- ATM machine program in C++
- Python | Create a function with a pass statement
- Python | Function to calculate the square root of a number
- Python | A function that calculates the power of a number
- Python | A function that accepts 2 integers and adds them and returns their sum
- Python | Function that takes a list of integers and returns the last integer
- Python | Return multiple values from a function