File I/O in Python

File I/O (Input/Output) is a crucial part of Python for working with files. Python provides a set of built-in functions and methods for file handling. Python perform operations like reading, writing, and manipulating file data.


Basic File Operations

Opening a File

Use the open() function to open a file.

Syntax:

open(file, mode)

Example

file = open('example.txt', 'r')
data = file.read()
file.close()
Warning

Always close a file after operations to release resources. Use with statements to handle files safely.


File Modes

When working with files, you can specify the mode in which the file is opened:

  • r: Read mode (default).
  • w: Write mode (overwrites the file if it exists).
  • x: Exclusive creation (fails if the file exists).
  • a: Append mode.
  • b: Binary mode.
  • t: Text mode (default).
  • +: Read and write mode.

Using with Statement

The with statement automatically closes the file.

with open('example.txt', 'r') as file:
    data = file.read()
print(data)
Warning

Always use with for file operations to ensure proper resource management and avoid file locks.


Reading Files

Python provides several methods for reading files:

read()

Reads the entire file or a specified number of characters.

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

readline()

Reads a single line from the file.

with open('example.txt', 'r') as file:
    line = file.readline()
    print(line)

readlines()

Reads all lines and returns them as a list.

with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)
Deep Dive

Use readlines() cautiously with large files, as it loads all lines into memory.

Info

For large files, avoid using read() or readlines() as they load the entire file into memory. Instead, iterate over the file object.

Iterating Through File Lines

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

Writing Files

You can write to files using methods like write() and writelines().

write()

Writes a string to the file.

with open('example.txt', 'w') as file:
    file.write("Hello, World!")

writelines()

Writes a list of strings to the file.

with open('example.txt', 'w') as file:
    file.writelines(["Line 1\n", "Line 2\n"])
Danger

When using 'w' mode, the file content is overwritten. Use 'a' mode to append data without erasing the existing content.

Info

Use \n to ensure lines are properly terminated.


File Pointer Control

Python allows precise control of the file pointer using seek() and tell().

seek(offset, whence)

Moves the file pointer to a specified location.

  • offset: Position to move to.
  • whence: Reference point (0 = start, 1 = current position, 2 = end).
with open('example.txt', 'r') as file:
    file.seek(5)
    content = file.read()
    print(content)

tell()

Returns the current position of the file pointer.

with open('example.txt', 'r') as file:
    print(file.tell())
Note

Use seek() and tell() for precise file pointer control, especially in binary files.


File Paths

When working with files, specifying the correct file path is crucial. Paths can be absolute or relative.

  • Absolute Path: Full path from the root directory.
  • Relative Path: Path relative to the current working directory.

Example

# Absolute path
with open('/Users/username/Documents/example.txt', 'r') as file:
    content = file.read()

# Relative path
with open('example.txt', 'r') as file:
    content = file.read()
Under Construction

Ensure file paths are cross-platform compatible by using the os or pathlib modules.


Handling Exceptions

File operations can fail due to reasons like file not found, permission errors, or file locks. Python provides robust exception handling mechanisms to manage such cases.

Example

try:
    with open('non_existent_file.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("The file does not exist.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"An error occurred: {e}")
Danger

Always handle exceptions to prevent crashes during file operations.


Other File Methods

flush() Method

Flushes the internal buffer to the file.

with open('example.txt', 'w') as file:
    file.write("Temporary data")
    file.flush()

Checking File Existence

Use the os module to check if a file exists.

import os
if os.path.exists('example.txt'):
    print("File exists.")

Deleting Files

import os
os.remove('example.txt')
Pitfall

Always check if the file exists before attempting to delete it to avoid errors.


File Structure Example

Example Project Structure

project/ ├── example.txt ├── read_file.py ├── write_file.py └── position_demo.py


Task

Practice: File Operations

Objective: Practice reading, writing, and controlling file pointers.

  1. Read File Content:

    • Create a function to read a file and print its content line by line.

    Example:

    def read_file(filename):
        with open(filename, 'r') as file:
            for line in file:
                print(line.strip())
    read_file('example.txt')
    
  2. Write File Content:

    • Write a program to write user input to a file.

    Example:

    def write_to_file(filename, content):
        with open(filename, 'w') as file:
            file.write(content)
    write_to_file('example.txt', "This is a test.")
    
  3. File Positioning:

    • Create a program to demonstrate the use of tell() and seek().

    Example:

    with open('example.txt', 'r') as file:
        print(file.tell())
        file.seek(5)
        print(file.read())
    
  4. Exception Handling:

    • Open a non-existent file and handle the FileNotFoundError gracefully.

    Example:

    try:
        with open('non_existent_file.txt', 'r') as file:
            content = file.read()
    except FileNotFoundError:
        print("The file does not exist.")
    
Info

Organize your file handling scripts and data files systematically for easier maintenance.


File I/O in Python is powerful and flexible. Mastering these operations is essential for any developer working with data or external resources.

Copyright © 2025 Devship. All rights reserved.

Made by imParth