DEV Community

M.T.Ramkrushna
M.T.Ramkrushna

Posted on

PYTHON ESSENTIALS FOR AI/ML(Working With Files)

πŸ“‚ 1. Why File Handling Matters

In real life you constantly work with files:

  • reading config files
  • storing logs
  • loading training data (CSV/JSON)
  • saving model outputs
  • writing results into text files

Python makes this very easy.


πŸ“„ 2. Opening a File (open())

Basic syntax:

file = open("filename.txt", "mode")
Enter fullscreen mode Exit fullscreen mode

Modes you must know:

Mode Meaning
"r" read (file must exist)
"w" write (overwrite existing file)
"a" append (add to existing file)
"x" create file (error if exists)
"b" binary mode (images, audio, etc.)
"t" text mode (default)

Real-life analogy

Mode = how you enter a room

  • r: you can only look
  • w: you can rewrite everything
  • a: you add more items without removing old ones

✍️ 3. Writing to a File

Example: saving user notes

file = open("notes.txt", "w")
file.write("Remember to practice Python daily!")
file.close()
Enter fullscreen mode Exit fullscreen mode

This creates/overwrites the file.

Append mode

file = open("notes.txt", "a")
file.write("\nToday's progress: Learned file handling.")
file.close()
Enter fullscreen mode Exit fullscreen mode

πŸ“– 4. Reading a File

Reading the whole file

file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()
Enter fullscreen mode Exit fullscreen mode

Reading line by line

file = open("notes.txt", "r")
for line in file:
    print(line.strip())
file.close()
Enter fullscreen mode Exit fullscreen mode

πŸ” 5. Important: Always Close the File

Not closing files can lock them or waste system resources.

Best practice: use with (autoclose)

with open("notes.txt", "r") as file:
    content = file.read()
Enter fullscreen mode Exit fullscreen mode

This automatically closes the file β€” ML/data engineers use this always.


πŸ“¦ 6. Real-Life Examples

🧾 Example 1: Saving user logs

with open("logs.txt", "a") as f:
    f.write("User logged in at 9:00 PM\n")
Enter fullscreen mode Exit fullscreen mode

πŸ“Š Example 2: Saving model predictions

predictions = [0.8, 0.2, 0.65]

with open("preds.txt", "w") as f:
    for p in predictions:
        f.write(str(p) + "\n")
Enter fullscreen mode Exit fullscreen mode

πŸ™‹ Example 3: Counting how many lines in a dataset

with open("data.txt") as f:
    count = len(f.readlines())
print("Lines:", count)
Enter fullscreen mode Exit fullscreen mode

πŸ§ƒ 7. Reading CSV Files (Without Pandas)

Real-life use: loading small datasets

with open("data.csv") as f:
    for line in f:
        values = line.strip().split(",")
        print(values)
Enter fullscreen mode Exit fullscreen mode

🧱 8. Writing to CSV Files

rows = [
    ["name", "age"],
    ["Ali", 25],
    ["Sara", 22]
]

with open("people.csv", "w") as f:
    for r in rows:
        f.write(",".join(map(str, r)) + "\n")
Enter fullscreen mode Exit fullscreen mode

πŸ“œ 9. Working With JSON Files (Super Useful in ML)

Write JSON

import json

data = {"name": "Ali", "skills": ["py", "ml"]}

with open("info.json", "w") as f:
    json.dump(data, f, indent=4)
Enter fullscreen mode Exit fullscreen mode

Read JSON

with open("info.json") as f:
    content = json.load(f)
print(content)
Enter fullscreen mode Exit fullscreen mode

Real-life use:

  • saving model configs
  • storing hyperparameters
  • reading APIs

πŸ–ΌοΈ 10. Working With Binary Files (Images, audio)

with open("photo.jpg", "rb") as f:
    data = f.read()

with open("copy.jpg", "wb") as f:
    f.write(data)
Enter fullscreen mode Exit fullscreen mode

🏁 11. Useful File-Related Operations (os module)

Check if file exists

import os

print(os.path.exists("notes.txt"))
Enter fullscreen mode Exit fullscreen mode

Delete a file

os.remove("notes.txt")
Enter fullscreen mode Exit fullscreen mode

List all files

print(os.listdir("."))
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ 12. Mini Exercises (Do these!)

Send your answers and I’ll check them.

Exercise 1

Write a note "Learning Python Files!" into learning.txt


Exercise 2

Read a file and print only lines that contain the word "error".


Exercise 3

Given a list of names, save each name on a new line in users.txt.


Exercise 4

Create a JSON file details.json containing:

  • name
  • age
  • skills (list)

Exercise 5

Copy an image a.jpg into backup/a_backup.jpg.

Top comments (0)