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: 
file1 = open(“example.txt”, “w”)  # Open file in write mode
file1.write(“Hello, this is a file handling example in Python.”)
file1.close()  # Always close the file
NB: If the file already exists, its content is overwritten.
Reading a File
file1 = open(“example.txt”, “r”)  # Open file in read mode
content = file1.read()  # Read entire file
print(content)
file1.close()
Other Read Methods
file1.read(10)    # Read first 10 characters
file1.readline()  # Read one line at a time
file1.readlines() # Read all lines as a list
Appending to a File
file1 = open(“example.txt”, “a”)  # Open file in append mode
file1.write(“\nThis is a new line added!”)  # Append data
file1.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 created and automatically closed.
with open(“example.txt”, “r”) as file:
    content = file1.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 = file1.read()
with open(“image2.jpg”, “wb”) as file:       # Write binary mode
    file.write(data)
Deleting/Removing a File or Directory
  • The ‘os’ module is used to delete a file.
import os
if os.path.exists(“example.txt”):
    os.remove(“example.txt”)  # Deletes the file
                    os.unlink(“example.txt”)  # Deletes the file
else:
    print(“File does not exist”)
  • To remove the directory or folders, os.rmdir() or shutil.rmtree() method is used.

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.