๐ CSV Processing
The csv module implements classes to read and write tabular data in CSV format.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import csv import io from pathlib import Path # 1. Write a CSV file programmatically fieldnames = ["username", "course", "score", "premium", "joined"] sample_data = [ {"username": "santoshtvk", "course": "Infinite Python", "score": 95, "premium": True, "joined": "2024-01-15"}, {"username": "dhruv", "course": "Infinite AI", "score": 88, "premium": True, "joined": "2024-02-20"}, {"username": "tvk", "course": "DevOps", "score": 72, "premium": False, "joined": "2024-03-01"}, {"username": "alice", "course": "Infinite Python", "score": 60, "premium": False, "joined": "2024-03-15"}, ] csv_path = Path("pynfinity_learners.csv") with open(csv_path, "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows(sample_data) print(f"Written {len(sample_data)} rows to {csv_path}") # 2. Read and filter with open(csv_path, "r", newline="", encoding="utf-8") as f: reader = csv.DictReader(f) all_rows = list(reader) premium = [r for r in all_rows if r["premium"] == "True"] print(f"Premium learners: {[r['username'] for r in premium]}") # 3. Aggregate โ average score scores = [float(r["score"]) for r in all_rows] print(f"Avg score: {sum(scores)/len(scores):.1f}") # 4. In-memory CSV (no file needed) output = io.StringIO() writer = csv.writer(output, delimiter="|") writer.writerow(["NAME", "COURSE", "SCORE"]) for r in all_rows: writer.writerow([r["username"], r["course"], r["score"]]) print("\nPipe-delimited CSV:") print(output.getvalue()) # 5. Update a field and rewrite for row in all_rows: row["score"] = str(min(int(float(row["score"])) + 5, 100)) # Bonus +5 with open(csv_path, "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows(all_rows) print("Updated CSV (bonus +5 applied):") for r in all_rows: print(f" {r['username']:<15} {r['score']}") # Cleanup csv_path.unlink(missing_ok=True)
Keep exploring and happy coding! ๐ป