File Operations

Python File Operations

File Input/Output and File Handling in Python

File operations are crucial for many programming tasks, allowing you to read from and write to files on your computer. Python provides powerful and easy-to-use functions for file handling.

1. File Input/Output

Opening a File

To work with a file, you first need to open it. The open() function is used for this purpose.

Syntax:

file = open(filename, mode)
  • filename: the name or path of the file
  • mode: specifies the purpose of opening the file (read, write, append, etc.)

Common modes:

  • 'r': Read (default)
  • 'w': Write (overwrites the file if it exists)
  • 'a': Append (adds to the end of the file)
  • 'x': Exclusive creation (fails if the file already exists)
  • 'b': Binary mode
  • 't': Text mode (default)

Example:

# Opening a file for reading
file = open('example.txt', 'r')

# Opening a file for writing
file = open('new_file.txt', 'w')

Closing a File

It's important to close a file after you're done with it to free up system resources.

file.close()

Using with Statement

The with statement is recommended as it automatically closes the file after you're done:

with open('example.txt', 'r') as file:
    # File operations here
    content = file.read()
    print(content)
# File is automatically closed outside the with block

Reading from a File

There are several methods to read from a file:

  1. read(): Reads the entire file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
  1. readline(): Reads a single line
with open('example.txt', 'r') as file:
    first_line = file.readline()
    print(first_line)
  1. readlines(): Reads all lines into a list
with open('example.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # strip() removes leading/trailing whitespace
  1. Iterating over the file object
with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

Writing to a File

  1. write(): Writes a string to the file
with open('new_file.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")
  1. writelines(): Writes a list of strings to the file
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('new_file.txt', 'w') as file:
    file.writelines(lines)

Appending to a File

To add content to the end of an existing file, use the 'a' mode:

with open('existing_file.txt', 'a') as file:
    file.write("\nThis line is appended.")

2. Text and Binary File Handling

Text Files

Text files contain human-readable characters. When working with text files, Python handles line endings and character encoding.

Example: Reading and writing a CSV file

import csv

# Writing to a CSV file
data = [
    ['Name', 'Age', 'City'],
    ['Alice', '30', 'New York'],
    ['Bob', '25', 'Los Angeles']
]

with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

# Reading from a CSV file
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(', '.join(row))

Binary Files

Binary files contain data in binary format, which is not human-readable. They are used for non-text data like images, audio files, etc.

Example: Copying an image file

# Copying a binary file (e.g., an image)
with open('original_image.jpg', 'rb') as source:
    with open('copy_image.jpg', 'wb') as dest:
        dest.write(source.read())

Working with JSON Files

JSON is a popular data format. Python's json module makes it easy to work with JSON data.

import json

# Writing JSON to a file
data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

with open('data.json', 'w') as file:
    json.dump(data, file, indent=4)

# Reading JSON from a file
with open('data.json', 'r') as file:
    loaded_data = json.load(file)
    print(loaded_data)

File Pointer and Seeking

You can move the file pointer to different positions using seek():

with open('example.txt', 'r') as file:
    file.seek(5)  # Move to the 6th byte in the file
    print(file.read(10))  # Read 10 characters from that position

Error Handling in File Operations

It's good practice to use try-except blocks when working with files:

try:
    with open('nonexistent_file.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("The file does not exist.")
except IOError:
    print("An error occurred while reading the file.")

Working with Paths

The os and pathlib modules provide functions for working with file paths:

import os
from pathlib import Path

# Using os
current_dir = os.getcwd()
file_path = os.path.join(current_dir, 'example.txt')

# Using pathlib
current_path = Path.cwd()
file_path = current_path / 'example.txt'

print(f"File exists: {file_path.exists()}")

Temporary Files

For temporary file operations, you can use the tempfile module:

import tempfile

with tempfile.TemporaryFile('w+t') as temp:
    temp.write('This is a temporary file')
    temp.seek(0)
    print(temp.read())
# File is automatically deleted after the with block

File operations are fundamental in many programming tasks. They allow you to persist data, read configurations, process large datasets, and much more. Understanding these concepts will greatly enhance your ability to work with files efficiently in Python.

Summary

File Input/Output:

  • Opening and closing files
  • Using the with statement
  • Reading from files (whole file, line by line, into a list)
  • Writing to files
  • Appending to files

Text and Binary File Handling:

  • Working with text files (including CSV example)
  • Handling binary files
  • JSON file operations
  • File pointer and seeking
  • Error handling in file operations
  • Working with file paths using os and pathlib
  • Using temporary files