Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
97: Working with CSV Files
Let's start with a piece of code that looks perfectly fine on the surface. Imagine you're writing a script to log some user data to a CSV file. You've got your list of users, you're using the csv module, and everything seems to be working. But when you open the resulting file in a text editor, you notice something annoying: there's a blank line between every single row of data.
import csv
users = [
["Alice", "Engineering"],
["Bob", "Marketing"],
["Charlie", "Sales"]
]
with open("users.csv", "w") as f:
writer = csv.writer(f)
writer.writerows(users)
The Mystery of the Double Newline
If you run this on Windows, you'll likely see those empty rows. It's a classic "gotcha." Here is what's happening: the csv.writer handles its own newline characters (specifically \r\n). However, Python's open() function, by default, uses "universal newline mode," which translates \n into the system's default line separator. On Windows, that means it sees the \n from the CSV writer and adds another \r, effectively doubling the line break.
The fix is simple, but it's one of those things you only learn once you've spent twenty minutes staring at a CSV file wondering why it's half-empty. You need to pass newline='' to the open function.
# The Correct Way
with open("users.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerows(users)
By setting newline='', we tell Python not to mess with the line endings, letting the csv module handle them exclusively. I always include this by default now; it saves a lot of headache.
Stop Counting Columns Manually
Most beginners start by using csv.reader, which returns each row as a list. That's fine for a file with two columns, but imagine a CSV with 30 columns. Writing row[14] in your code is a nightmare—you'll spend half your day counting commas in a text editor just to figure out which index corresponds to "Shipping Address."
Instead, I want you to get comfortable with csv.DictReader. It treats the first row of your CSV as headers and turns every subsequent row into a dictionary. This makes your code significantly more readable and much more resilient if the column order in the source file changes.
import csv
with open("employees.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
# Instead of row[0], we use the actual header name
print(f"Employee {row['Name']} works in {row['Department']}")
Writing Data with DictWriter
If you're reading data as dictionaries, it only makes sense to write them that way too. The csv.DictWriter class allows you to pass in a list of fieldnames (your headers) and then write rows as dictionaries. The biggest hurdle here is remembering that DictWriter doesn't automatically write the header row for you—you have to call a specific method for that.
import csv
data = [
{"Name": "Alice", "Role": "Dev", "Level": 3},
{"Name": "Bob", "Role": "Designer", "Level": 2},
]
fields = ["Name", "Role", "Level"]
with open("staff.csv", "w", newline='') as f:
writer = csv.DictWriter(f, fieldnames=fields)
# Don't forget this part, or your CSV will have no headers!
writer.writeheader()
writer.writerows(data)
One quick tip: if your dictionary has more keys than the fieldnames list, DictWriter will raise a ValueError. If you want it to just ignore the extra keys, you can pass extrasaction='ignore' to the constructor. It's a lifesaver when you're dealing with messy API responses that you're dumping into a CSV.
📋 Practical Task
Inventory Value Calculator
You have been handed a CSV file named inventory.csv with the following content:
Product,Quantity,PricePerUnit
Laptop,10,1200
Mouse,50,25
Keyboard,30,75
Monitor,15,300
Write a Python script that does the following:
- Reads
inventory.csvusingcsv.DictReader. - Calculates the total value for each item (Quantity × PricePerUnit).
- Calculates the grand total value of the entire inventory.
- Prints each product and its total value, followed by the grand total.
Laptop: $12000 Mouse: $1250 Keyboard: $2250 Monitor: $4500 Grand Total: $20000
There are no comments for now.