



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A comprehensive guide to file handling in python, covering essential operations such as reading, writing, and appending to files. It includes practical examples, syntax explanations, and debugging tips to help users effectively manage files in their python programs. The guide also emphasizes best practices like using the 'with' statement for safer file handling and provides practice questions to reinforce learning. This resource is ideal for students and developers looking to master file i/o in python.
Typology: Lecture notes
1 / 7
This page cannot be seen from the preview
Don't miss anything!




In real-world programming, we often need to store data permanently —like saving student records, logs, or results. That’s where file handling comes in. Python makes it easy to read , write , and update files using simple commands. Whether it's a .txt, .csv, or .json file, mastering file handling is essential for building real applications. 🗒 Sticky Note : File handling = talking to your computer’s memory. You read from it, write to it, and save your work.
Store data between program runs Save user input, logs, or reports Read configuration files
📘 Example: python file = open("data.txt", "r") content = file.read() print(content) file.close() 📘 Other Methods: readline() → reads one line readlines() → reads all lines as a list 🗒 Quick Tip : Use .strip() to remove extra spaces or newline characters.
📘 Example: python file = open("data.txt", "w") file.write("Hello, Zano!") file.close() 📘 Explanation: "w" mode overwrites the file Use \n to add new lines 🗒 Sticky Note :
"w" mode erases old content. Use "a" if you want to keep it.
📘 Example: python file = open("data.txt", "a") file.write("\nNew line added.") file.close() 🗒 Quick Tip : Appending is useful for logs, history, or adding new entries.
Always close the file after you're done to free system resources. python file.close() 🗒 Sticky Note : Think of closing a file like shutting a notebook—don’t leave it open!
Error Type Cause Fix FileNotFoundError File doesn’t exist Check filename or path IOError File is locked or unreadable Use correct mode and permissions ValueError Wrong mode or operation Match method with mode 🗒 Quick Tip : Use try-except blocks to handle errors gracefully.
Use open() with correct mode ("r", "w", "a") Always close() the file or use with Use read(), write(), append() based on your task Handle errors with care