📂

File Handling in Python

Jul 3, 2024

Lecture on File Handling in Python

Introduction

  • Sequential data types previously covered: lists, tuples, sets
  • Basic operations and inbuilt functions discussed
  • Focus today: Files in Python

Concept of Files

  • Purpose: Store output data
  • In programming, files allow the saving of output data
  • Types of Files: Text Files & Binary Files

Basic File Operations

  • Opening & Creating Files

    • Before reading or writing, a file must be created and opened
    • Use the open function to open/create files
    • Syntax: file_object = open('filename.txt', 'access_mode')
    • File object (file pointer) points to the file's content
  • Access Modes

    • Define how files are to be accessed (read/write)
    • Primary Access Modes: R, W, A
      • r (Read Mode)
        • File should exist; file's content read-only
        • Pointer at the beginning of the file
      • w (Write Mode)
        • File opened for writing; overwrites existing content
        • If the file doesn't exist, a new file is created
      • a (Append Mode)
        • Append data to existing content
        • Pointer at the end; creates file if it doesn’t exist
    • Extended Access Modes
      • r+, w+, a+ for both reading and writing in text files
      • rb, wb, ab for binary files
      • rb+, wb+, ab+ for both reading and writing in binary files
  • File Closing

    • It's the user's responsibility to close opened files
    • Syntax: file_object.close()
    • Example: fp = open('abc.txt', 'w') # perform operations fp.close()

Example

# Opening a file in write mode fp = open('abc.txt', 'w') # Writing operation fp.write('Hello World') # Closing the file fp.close()

Summary

  • Steps to handle files: Open, Read/Write, Close
  • File creation: Occurs in write (w) and append (a) modes
  • Importance of closing files after operations

Next Session: Reading & Writing Operations on Files

If there are any doubts or queries, feel free to ask in the comments.

Thank you for listening and don't forget to subscribe!