Loading

Quipoin Menu

Learn • Practice • Grow

python-for-ai / File Handling
tutorial

File Handling

AI projects often need to read data from files (CSV, text, images) and save results (trained models, logs). Python provides simple ways to handle files.

Opening and Reading Files

Use open() with a mode: r for read, w for write, a for append.
# Read a text file line by line
with open('data.txt', 'r') as file:
for line in file:
print(line.strip())

Writing to a File

# Write predictions to a file
with open('predictions.txt', 'w') as f:
for pred in [0.1, 0.8, 0.3]:
f.write(str(pred) + 'n')

Reading CSV Files for AI

CSV (comma‑separated values) is a common data format. Python’s built‑in csv module helps.
import csv

with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row) # row is a list of values

Why File Handling Matters for AI

  • Load training datasets from CSV, JSON, or images.
  • Save model checkpoints (weights) during training.
  • Write logs and evaluation metrics.
  • Read configuration files for hyperparameters.

Best Practice: Use with Statement

The with block automatically closes the file, even if an error occurs. Always prefer it over manual open() and close().


Two Minute Drill
  • open('file', 'r') reads, 'w' writes, 'a' appends.
  • Use with open(...) as f: to auto‑close the file.
  • Read lines with for line in f:.
  • CSV files are common for AI datasets; use csv.reader.

Need more clarification?

Drop us an email at career@quipoinfotech.com