File handling is a way to read, write, update, and delete files in Python. It's useful when working with logs, reports, documents, and storing data persistently.
Python has built-in functions to create, open, read, write, and close files.
We will mostly deal with text files here.
Use the built-in open()
function.
file = open("example.txt", "r")
Mode | Description |
---|---|
"r" |
Read (default), file must exist |
"w" |
Write, creates new or truncates existing file |
"a" |
Append, adds to the end |
"x" |
Create, fails if file exists |
"b" |
Binary mode (e.g. "rb" or "wb" ) |
"t" |
Text mode (default, used like "rt" ) |
read()
: Read entire content