1.9 File Handling (read, write CSV)

Loading content...

1.9 File Handling (read, write CSV)

Module 9 — File Handling 📂 | Python for ML 🤖 Module 9 • Python for Machine Learning Read data from files, write results, work with CSV datasets and JSON configs — the skills every ML engineer uses daily! 🚀 🏠 Daily-life analogy: Think of your computer as a kitchen 🍳. The RAM (memory) is your countertop — you prepare food there, but when you leave, it gets cleaned. The hard drive is your pantry — food stored there stays until you remove it. 📂 File handling is the act of moving things between the countertop (RAM) and the pantry (disk). When your Python program ends, all variables vanish — unless you save them to a file. 📖 File Handling = Reading data from files into your program, or writing data from your program into files — so data persists even after the program ends. 🤖 In Machine Learning, almost everything is files: 📊 Datasets arrive as CSV files 🔧 Configuration is stored in JSON files 📝 Training logs go into text files 💾 Model predictions are saved to CSV 📈 Results are exported for reporting 📄 Files on Disk (permanent) Data survives even after program ends! 💪 ✅ True or False — Activity 1 When a Python program ends, all variables in RAM are lost unless saved to a file. 🤔 Before we touch any code, let's learn the essential terms 📚 Opens a file, creates a connection Closes the file, frees resources Putting the book back on the shelf 📚 Reads entire file content as one string Reading the whole book at once 👀 Reading one page at a time 📄 Writing in your notebook ✏️ Specifies how to open the file (r/w/a) Deciding if you'll read, write, or add to the book 📝 Auto-closes file when done Comma-Separated Values file A spreadsheet saved as plain text 📊 JavaScript Object Notation (data format) A neatly organized dictionary 📋 Match each term to its correct description 🧩 Reads entire file as one string 🔓 Opening Files — Modes Explained 🚪 Before you read or write, you must open the door to the file. The open() function does this. You also tell Python what you plan to do — that's the mode. file = open("filename.txt", "mode") 📖 Read only. Cannot write. ✏️ Write only. Overwrites existing content! ➕ Adds to the end. Keeps existing content. ⚠️ Danger! Mode "w" erases everything in the file before writing. If you want to add without deleting, use "a" (append) instead! 💡 Default mode is "r" (read). So open("data.txt") is the same as open("data.txt", "r"). Like going to a library to read a book. You can look at it, but you can't change it. The book must exist! 📚 Like getting a brand new notebook. Even if the old one had writing, it's erased and you start fresh. 📒 Like adding entries to your diary. You don't erase old pages — you just write after the last entry. 📔 Like an editable document. You can read what's there AND make changes. But the file must already exist. 📝 🧠 Quick Check — Activity 3 You want to add new log entries to an existing log file without erasing old logs. Which mode should you use? 📝 📖 Reading Files — Three Ways Python gives you three methods to read file contents. Think of it like reading a book 📚: read() — Read the ENTIRE book at once Returns one big string with all the content. Good for small files. ⚡ readline() — Read ONE page at a time Returns a single line. Call it again to get the next line. 📄 readlines() — Get a LIST of all pages Returns a list where each element is one line. Perfect for looping! 📋 📖 Three ways to read — comparing all three # Assume "data.txt" contains: # Method 1: read() — entire file as one string print(content) # prints all 3 lines # Method 2: readline() — one line at a time line1 = f.readline() # "Hello World\n" line2 = f.readline() # "Python is fun\n" # Method 3: readlines() — list of all lines print(lines) # ['Hello World\n', 'Python is fun\n', ...] 📌 Key insight: After reading, the "cursor" moves forward. If you call read() twice on the same file object, the second call returns an empty string — the cursor is already at the end! Watch how data flows from a file into your Python program 👆 Press Play to see how file reading works step by step! 🧠 Quick Check — Activity 4 What does readlines() return? 📋 A single string with all content A list where each element is one line Just the first line of the file The number of lines in the file 📝 Writing is the reverse of reading — data flows from your program into a file on disk. Writes a single string to the file. Does NOT add a newline — you must add \n yourself! ✏️ Writes a list of strings. Again, no automatic newlines between items! 📋 f = open("output.txt", "w") f.write("Python is great\n") # writelines() — list of strings lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

Subject: Python for Machine Learning | Chapter: Chapter 1: Python Essentials

1.8 String Operations Chapter 1: Python Essentials 2.1 NumPy Arrays and Operations
Topics
Chapter 1: Python Essentials
Chapter 2: Python for Data Science
© Copyright © 2020 ALGOPK . All Rights Reserved.