
File Handling in Python
File handling is an important topic in Python. It allows us to create, read, write, and manage files using Python programs. File handling is useful when we want to store information permanently instead of keeping it only in the program.
What is File Handling?
File handling means working with files such as .txt , .csv , and other files using Python.
Opening a File
Python provides a simple open() function to open and work with files.
The basic syntax is:
file = open("filename.txt", "mode")
Here, filename.txt is the file name and mode tells Python what we want to do with the file.
Closing a File
The file.close() method is used to closes the file after performing file operations or tasks
file = open("filename.txt", "mode")
#perform file operations
file.close()File Opening Modes
Some commonly used modes are:
- r – Read the file
- w – Write to the file
- a – Add new content to the file
- x – Create a new file
Reading a File
We can use read() to read the content of a file, the r mode is used to read the file.
file = open("sathwik.txt", "r")
content = file.read()
print(content)
file.close()
This program opens the file, reads its content, prints it, and then closes the file.
Writing to a File
The w mode is used to write data into a file.
The write() method is used to add content.
file = open("sathwik.txt", "w")
file.write("Hello, my name is Sathwik.")
file.close()
If the file does not exist, Python will create it. If it already exists, the old content will be replaced.
Appending Data
The a mode is used when we want to add new content without deleting the existing content.
file = open("sathwik.txt", "a")
file.write("\nI am learning Python.")
file.close()
The new sentence will be added at the end of the file.
Creating a new file
The x mode is used to create a new file. If the file already exists, Python will show an error.
file = open("sathwik.txt", "x")
file.write("Hello, my name is Sathwik.")
file.close()Here, Python creates a new file named sathwik.txt and writes the given text into it.
Using with Statement
A better way to work with files is by using the with statement. It automatically closes the file after the work is completed.
with open("sathwik.txt", "r") as file:
content = file.read()
print(content)
This is simple and safer because we don't need to manually write file.close()
Join Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments