Introduction

  • File handling in Python allows us to read, write, and manipulate files (text or binary) stored on our system.
  • Python provides several built-in functions to work with files such as open(), remove(), write(), etc.

Definition

  • A file in Python is a storage unit on a computer where data can be stored permanently.

File Modes in Python

Mode  :   Description
“r” : Read (default) – Opens file for reading; error if file doesn’t exist.
“w” : Write – Creates a file if it doesn‘t exist; overwrites if it exists.
“a” : Append – Opens file for writing; does not overwrite existing content.
“x” : Exclusive creation – Creates a new file; fails if file exists.
“t” : Text mode (default) – Handles text files.
“b” : Binary mode – Handles binary files (images, videos, etc.).

Types of Files in Python

Two types –

Text Files (.txt, .csv, .log)
    • These files store readable characters (letters, numbers, symbols).
    • Example: “Hello, World!” in a .txt file.
Binary Files (.jpg, .pdf, .exe)
    • These files store non-readable data (machine code).
    • Example: Images, videos, executables.

File Operations

🔹 Opening a File
Syntax: 
file = open(“filename.txt”, “mode”)
where, “filename.txt” → The name of the file.
“mode” → Specifies how the file is opened (read, write, append, etc.).
🔹 Writing to a File
Syntax: 
file = open(“example.txt”, “w”)  # Open file in write mode
file.write(“Hello, this is a file handling example in Python.”)
file.close()  # Always close the file
NB: If the file already exists, its content is overwritten.
🔹 Reading a File
file = open(“example.txt”, “r”)  # Open file in read mode
content = file.read()  # Read entire file
print(content)
file.close()
Other Read Methods
file.read(10)    # Read first 10 characters
file.readline()  # Read one line at a time
file.readlines() # Read all lines as a list
🔹 Appending to a File
file = open(“example.txt”, “a”)  # Open file in append mode
file.write(“\nThis is a new line added!”)  # Append data
file.close()
NB : It does not overwrite existing content; it just appends at the end.
🔹 ‘with’ Statement in File
  • Using the ‘with’ statement, the file is automatically closed.
with open(“example.txt”, “r”) as file:
    content = file.read()
    print(content)  # File closes automatically after the block
🔹 Working with Binary Files
  • This is applied for images, PDFs, etc.
with open(“image1.jpg”, “rb”) as file:         # Read binary mode
    data = file.read()
with open(“image2.jpg”, “wb”) as file:       # Write binary mode
    file.write(data)
🔹 Deleting a File
  • The ‘os’ module is used to delete a file.
import os
if os.path.exists(“example.txt”):
    os.remove(“example.txt”)  # Deletes the file
else:
    print(“File does not exist”)

Loading

Categories: Python Theory

0 Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.