📁 File Handling in Python
Working with Files Easily
🔹 DefinitionFile handling in Python refers to the process of creating, opening, reading, writing, and closing files using a Python program.
In simple words, file handling allows a program to store data permanently on a computer and retrieve it later when needed. Unlike variables, which lose their data when the program stops running, files keep data saved for future use.
File handling is very important for real-world applications such as saving user information, logs, reports, and records.
📌 Basic Syntax of File Handling
file = open("filename", "mode")
# perform operations
file.close()
Python also provides a safer method using with:
with open("filename", "mode") as file:
# perform operations
📂 Common File Modes
- r → Read
- w → Write
- a → Append
- x → Create
- rb → Read binary
- wb → Write binary
✍️ Example 1: Writing to a File
file = open("data.txt", "w")
file.write("Hello, this is file handling in Python.")
file.close()
This code creates a file named data.txt and writes text into it. If the file already exists, its old content is removed.
📖 Example 2: Reading from a File
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
The file is opened in read mode, and the content is displayed on the screen.
➕ Example 3: Appending Data to a File
file = open("data.txt", "a")
file.write("<br/>This line is added later.")
file.close()
Append mode adds new data at the end of the file without deleting existing content.
🔐 Example 4: Using with Statement
with open("data.txt", "r") as file:
print(file.read())
The with statement automatically closes the file, making the code safer and cleaner.
🔑 Key Points to Remember
- Files allow permanent data storage
- Always close files after use
- with statement is safer and recommended
- Different modes control file behavior
📌 Conclusion
File handling in Python helps programs store and manage data efficiently. It is simple, powerful, and essential for building real applications. Understanding file handling allows developers to work with real-world data easily.