File Handling in Python
Introduction
This lesson is part of our complete Python course for beginners. In this lesson, you will learn file handling in Python and how to read from and write to files.
Understanding file handling in Python for beginners is important because real-world applications need to store and retrieve data.
What is File Handling in Python?
File handling in Python allows you to create, read, write, and manage files on your system.
Opening a File
You can open a file using the open() function.
Example:
file = open(“data.txt”, “r”)
Reading a File
read()
file = open(“data.txt”, “r”)
print(file.read())
readline()
file = open(“data.txt”, “r”)
print(file.readline())
Writing to a File
write()
file = open(“data.txt”, “w”)
file.write(“Hello Python”)
File Modes in Python
- r (read)
- w (write)
- a (append)
- x (create)
Closing a File
Always close the file after use.
file.close()
Using with Statement (Best Practice)
with open(“data.txt”, “r”) as file:
print(file.read())
Why File Handling is Important
File handling in Python helps you:
- Store data permanently
- Read and process data
- Build real-world applications
Therefore, understanding file handling in Python for beginners is essential.
Internal Link
Explore full Python Course for Beginners
Conclusion
Now you understand file handling in Python including reading, writing, and managing files.
In the next lesson, you will learn exception handling in Python.
Next Lesson
Exception Handling in Python



