Python Files I/O

File I/O(Input/Output) in Python allows a program to read from and write to files stored on a system. This is an important function for handling persistent data, such as saving user input, reading configuration files, or working with logs.

Key Concepts

  1. File Modes:
    When working with files, Python provides several modes for opening a file. Each mode determines the file’s behavior:
  • 'r' (read): Opens a file for reading. It throws an error if the file doesn’t exist.
  • 'w' (write): Opens a file for writing, creating the file if it doesn’t exist. If it exists, it truncates (clears) the file before writing.
  • 'a' (append): Opens a file for writing. It adds content at the end of the file. If the file doesn’t exist, then it will create one.
  • 'b' (binary): This mode is used to deal with binary files, for example, images and videos. Generally, it’s combined with other modes such as 'rb' or 'wb'.
  • 'x' (exclusive creation): Opens a new file and throws an error if the file already exists.
  • 't' (text): This is the default mode when dealing with text files.

2. Basic Steps:

  • Open a file using open().
  • Perform operations like read/write.
  • Close the file using close() to free resources.

3. Context Manager (with Statement):
Using with is the recommended way of working with files. It ensures that the file is closed properly after operations, even if an error occurs.

File I/O Operations

1. Opening a File

file = open('example.txt', 'r') # Opens the file in read mode

2. Reading from a File

  • Read the Entire File:
with open('example.txt', 'r') as file:
  content = file.read()
  print(content)
  • Read Line by Line:
with open('example.txt', 'r') as file:
   for line in file:
     print(line.strip()) # Removes newline characters
  • Read a Specific Number of Characters:
with open('example.txt', 'r') as file:
    partial_content = file.read(10) # Reads the first 10 characters
    print(partial_content)

3. Writing to a File

  • Write a Single Line:
with open('example.txt', 'w') as file:
  file.write("Hello, World!")
  • Write Multiple Lines:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('example.txt', 'w') as file:
   file.writelines(lines)

4. Appending to a File:

with open('example.txt', 'a') as file:
    file.write("This is an appended line.\n")

5. Closing a File:

file = open('example.txt', 'r')
# Perform operations
file.close()

Working with Binary Files

  • Reading Binary Data:
with open('image.jpg', 'rb') as file:
   data = file.read()
  • Writing Binary Data:
with open('output.jpg', 'wb') as file:
  file.write(data)

File Pointer Operations

The file pointer marks the current position in the file:

  1. Move Pointer: file.seek(offset, from_what)
  • offset: Number of bytes to move.
  • from_what:
    • 0: Beginning of the file (default).
    • 1: Current position.
    • 2: End of the file.

2. Get Current Position: file.tell()

with open('example.txt', 'r') as file:
file.seek(5) # Move pointer to 5th byte
print(file.read()) # Start reading from the 5th byte

Checking File Existence

Use the os or pathlib module:

import os
if os.path.exists('example.txt'):
    print("File exists")
else:
    print("File does not exist")

Advantages of Using File I/O

  1. Persistent storage.
  2. Easy to manage logs, configuration files, and external datasets.
  3. Supports large data handling (e.g., file streams for massive files).