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:
- Google Unveils Veo 2 and Imagen 3: A New Era of AI-Generated Content
- Imagination to Reality, Unlocking the Future: Genesis Physics Engine for 4D Simulation
- Simple Code to compare Speed of Python, Java, and C++?
- Falling Stars Animation on Python.Hub October 2024
- Most Underrated Database Trick | Life-Saving SQL Command
- Python List Methods
- Top 5 Free HTML Resume Templates in 2024 | With Source Code
- How to See Connected Wi-Fi Passwords in Windows?
- 2023 Merry Christmas using Python Turtle
- 23 AI Tools You Won’t Believe are Free
- Python 3.12.1 is Now Available
- Best Deepfake Apps and Websites You Can Try for Fun
- Amazon launched free Prompt Engineering course: Enroll Now
- 10 GitHub Repositories to Master Machine Learning
- Hello World in 35 Programming Languages
- How to Scrape Data From Any Website with Python?
- Become Job Ready With Free Harvard Computer Science course: Enroll Now
- Free Python Certification course from Alison: Good for Resume
- Download 1000+ Projects, All B.Tech & Programming Notes, Job, Resume & Interview Guide, and More – Get Your Ultimate Programming Bundle!
- Udacity Giving Free Python Course: Here is how to Enroll
- Love Babbar’s Income Revealed
- Top 5 Websites to Learn Programming in 2024
- Python Internship for college students and freshers: Apply Here
- Microsoft Giving Free Python Course in 2023: Enroll Now
- Top 5 Free Python Courses on YouTube in 2024
- Complete Python Roadmap for Beginners in 2024
- New secrets to Earn money with Python in 2024
- Connect with HR Directly – Job Hack
- Google offering free Python course: Enroll Today