codegurukool.com · Free coding tutorials & online compiler

Home › Python Tutorial › Python file handling

Python file handling

Read, write and delete files.

open(name, mode) uses modes "r" read, "w" write (replaces the file) and "a" append. The with statement closes the file automatically. os.remove deletes a file.

Example code

import os
with open("notes.txt", "w") as f:
    f.write("Hello file")
with open("notes.txt") as f:
    print(f.read())
os.remove("notes.txt")
print(os.path.exists("notes.txt"))

Run this code in the online editor

← Python encapsulation and magic methodsNumPy, Pandas and Matplotlib →