Learn how to handle text and binary files in Python using common open modes and practical examples.
Working with Files in Python

Python and file handling

Python provides straightforward APIs to open, read, write, and close files. File mode determines whether you read, overwrite, or append data.

Running the script

Save your code as files.py and run it from terminal.

Text files

Main modes are r, w, and a. Use w to overwrite and a to append.

Binary files

Use rb, wb, and rb+ for byte-level operations.

f = open("demofile.txt", "w")
f.write("New content")
f.close()

seek and cursor control

The seek() method moves the read/write cursor to a specific position, useful in binary formats.