Oct 3
Oct 3
Handout
File Handling in Python: Student Handout
Welcome to the session on File Handling in Python! This guide will help you understand
how to work with files in Python, including reading, writing, and appending data. Let's dive
into the key concepts and examples.
2. Opening a File
To work with a file, you must first open it using the open() function.
Syntax:
File Modes:
"r" : Read mode
"w" : Write mode
"a" : Append mode
"r+" : Read and write mode
Examples:
1. Open a file for reading:
Examples:
1. Read the entire file:
4. Writing to a File
To write data to a file, open it in write ( "w" ) or append ( "a" ) mode.
Examples:
1. Write to a file (overwrite):
2. Append to a file:
5. Closing a File
Always close a file after use to free up system resources.
Example:
file.close()
file.close()
print("The sum of the numbers is:", total)
Popular Libraries:
math: Mathematical functions
datetime: Date and time functions
os: Operating system interactions
sys: System-specific parameters and functions
filename = "example.txt"
try:
if os.path.exists(filename):
file = open(filename, "r")
print(file.read())
file.close()
else:
print(f"The file {filename} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
Conclusion
In this session, you learned about file handling in Python, including:
Key Takeaways:
Always close a file after use.
Choose the appropriate file mode for your task.
Handle errors using try-except blocks.
This handout should take approximately 10-15 minutes to read. Feel free to practice the
examples and ask questions if needed!