HOME HTML EDITOR C JAVA PHP python

Python File Handling

File handling in Python lets you create, read, update, and delete files stored on disk using the built-in open() function. Common modes include "r" (read), "w" (write/overwrite), and "a" (append).

1. Reading a File with with open()

Using a with statement automatically closes the file when the block finishes, even if an error occurs:

with open("notes.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

2. Writing & Appending to a File

Mode "w" creates a new file or overwrites existing content, while mode "a" adds new text to the end of the file:

# Overwrite or create file
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("Session started.\n")

# Append to existing file
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("User logged in.\n")

3. Checking & Deleting a File

Use Python's os module to check if a file exists before deleting it with os.remove():

import os

if os.path.exists("temp.txt"):
    os.remove("temp.txt")
    print("File deleted.")
else:
    print("File does not exist.")
Important: Opening an existing file in "w" mode erases its previous contents immediately — use "a" whenever you want to preserve existing lines.