Press ESC to close

Python File Handling

  • File Modes

ModeDescription
"r"Read (default)
"w"Write (creates or overwrites)
"a"Append (adds data at the end)
"x"Create a new file (fails if it exists)
"rb"Read binary files
"wb"Write binary files
  • Use with Statement

    • The with statement automatically closes the file.
       

 1. Writing ("w")

with open("example.txt", "w") as file:
   print(file.file.write("Python File Handling"))

 2. Reading ("r")

with open("example.txt", "r") as file:
   print(file.read()) 

 3. Append Mode ("a")

with open("example.txt", "a") as file:
    file.write("\nWelcome to Python")


 4. Create Mode ("x")

If the file already exists, Python raises a FileExistsError.

with open("example.txt", "x") as file:
   file.write("Python File Handling")

5. Binary Read Mode ("rb")

Purpose: Reads binary files such as images, PDFs, videos, ZIP files, etc.

with open("photo.jpg", "rb") as file:
   data = file.read()
print(type(data))
  • Checking if a File Exists

import os

if os.path.exists("example.txt"):
   print("File exists")
else:
   print("File not found")
  • Deleting a File

import os

if os.path.exists("example.txt"):
   os.remove("example.txt")

When should you use each?

  • "a" → Add logs, user records, or new entries without deleting old data.
  • "x" → Ensure you don't accidentally overwrite an existing file.
  • "rb" → Read non-text files like images, PDFs, or videos.
  • "wb" → Save or copy binary files such as images, PDFs, audio, or downloaded content.

 

 

Related Posts

Python Error Handling Explained | Try, Except, Else & Finally
Python Class
Python Functions
Python Dict & Tuples

Leave a comment

Your email address will not be published. Required fields are marked *

Your experience on this site will be improved by allowing cookies.