File handling in Python is a crucial aspect of data processing, enabling the reading from and writing to files stored on disk. Python provides a robust set of built-in functions and modules to perform file operations, ensuring efficient interaction with different file formats. Below, we’ll cover the basics of file handling, including reading from and writing to text and binary files, modes, and proper error handling practices. We’ll also demonstrate how to work with CSV and JSON files and write logs effectively.

### Basic File Operations

#### Opening and Closing Files

In Python, files are opened using the `open()` function, which returns a file object:

“`python
file = open(‘filename.txt’, mode)
# Perform operations using the file object
file.close() # Ensure the file is properly closed
“`

However, using a context manager is the recommended approach as it automatically handles file opening and closing, even if an error occurs:

“`python
with open(‘filename.txt’, mode) as file:
# Perform operations using the file object
pass
“`

### File Modes

– **’r’**: Read mode (default). Opens a file for reading. Raises an error if the file does not exist.
– **’w’**: Write mode. Opens a file for writing. Creates the file if it does not exist or truncates the file if it exists.
– **’a’**: Append mode. Opens a file for appending new data at the end. Creates the file if it does not exist.
– **’rb’**: Read binary mode. Opens a file for reading in binary format.
– **’wb’**: Write binary mode. Opens a file for writing in binary format.

Example of reading and writing text files:

“`python
# Writing to a file
with open(‘example.txt’, ‘w’) as file:
file.write(“Hello, World!”)

# Reading from a file
with open(‘example.txt’, ‘r’) as file:
content = file.read()
print(content)
“`

### Reading CSV and JSON Files

#### CSV Files

CSV (Comma-Separated Values) files can be read using the `csv` module:

“`python
import csv

# Reading a CSV file
with open(‘data.csv’, ‘r’) as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
print(row)

# Writing to a CSV file
with open(‘output.csv’, ‘w’, newline=”) as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow([‘Name’, ‘Age’, ‘City’])
csv_writer.writerow([‘Alice’, ’30’, ‘New York’])
“`

#### JSON Files

JSON (JavaScript Object Notation) files can be handled using the `json` module:

“`python
import json

# Reading a JSON file
with open(‘data.json’, ‘r’) as json_file:
data = json.load(json_file)
print(data)

# Writing to a JSON file
data_to_save = {‘Name’: ‘Alice’, ‘Age’: 30, ‘City’: ‘New York’}
with open(‘output.json’, ‘w’) as json_file:
json.dump(data_to_save, json_file, indent=4)
“`

### Writing Logs

Python provides a `logging` module for creating log files:

“`python
import logging

# Basic configuration for logging
logging.basicConfig(filename=’app.log’, level=logging.INFO, format=’%(asctime)s – %(levelname)s – %(message)s’)

# Writing logs
logging.info(‘This is an informational message.’)
logging.error(‘This is an error message.’)
“`

### Error Handling

When dealing with files, errors may occur, such as a missing file or permission issues. We can handle these errors using `try-except` blocks:

“`python
try:
with open(‘non_existent_file.txt’, ‘r’) as file:
content = file.read()
except FileNotFoundError:
print(“The file does not exist.”)
except IOError as e:
print(f”An I/O error occurred: {e}”)
“`

### Reading and Writing Binary Files

Binary files such as images or executable files can be read and written using `rb` and `wb` modes:

“`python
# Reading a binary file
with open(‘image.png’, ‘rb’) as binary_file:
data = binary_file.read()

# Writing a binary file
with open(‘output_image.png’, ‘wb’) as binary_file:
binary_file.write(data)
“`

In summary, Python’s file handling capabilities allow for seamless reading and writing of both text and binary files using various modes. Context managers ensure safe operations with minimal code, while modules like `csv` and `json` facilitate interacting with structured data formats. Proper error handling is essential for building robust applications that deal with file operations.

Scroll to Top