Ad space (banner)
🐍Python Lessons
Lesson 14 / 69

File Handling Basics

This lesson covers the basics of file handling in Python using open() and the with statement, so you can safely read and write files. It's written for anyone searching "Python file read write" or "Python with open".

open() opens a file, and combining it with a with statement automatically closes the file once you're done. You write it as with open(filename, mode) as f:, where mode is "w" for writing or "r" for reading.

The sample code first opens a file in "w" mode and writes two lines of text, then reopens it in "r" mode, reads the contents with .read(), and prints them. The file is automatically closed the moment execution leaves the with block, so there's no need to call close() explicitly.

A common beginner mistake is not realizing that opening a file in "w" mode overwrites and erases any existing content. If you want to add to existing content instead, use "a" (append) mode. Not using with risks forgetting to close the file, which is why this pattern is the recommended default in real code.

File handling is a widely applicable basic skill in real applications — logging, reading and writing config files, and more. Reading CSV files or handling JSON config files, more advanced operations you'll meet later, all build on this same open() foundation.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)