Master reading and writing CSV files in Python in 60 seconds! 🐍 In this beginner-friendly tutorial, you’ll learn how to read CSV in Python, how to write CSV in Python, and when to use the built-in csv module vs pandas.read_csv and DataFrame.to_csv. Perfect for Python beginners, data analysis, and quick automation.
💡 What you’ll learn
• Read CSV with csv.reader and csv.DictReader
• Write CSV with csv.writer and csv.DictWriter
• One-liners with pandas.read_csv / to_csv(index=False)
• Common gotchas: UTF-8 encoding, newline='' on Windows, delimiters (;), quoting
🧩 Code used
Built-in csv
import csv
with open("data.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
name, score = row[0], int(row[1])
print(name, score)
with open("out.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f); writer.writerows([["name","score"],["Alice",92]])
DictReader / DictWriter
with open("data.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], int(row["score"]))
with open("out.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["name","score"])
w.writeheader(); w.writerow({"name":"Cara","score":99})
pandas
import pandas as pd
df = pd.read_csv("data.csv")
df.to_csv("out.csv", index=False)
⛏️ Pro tips
• Numbers arrive as strings → cast with int() / float()
• Custom separator → delimiter=';'
• Quoting → quotechar='"', quoting=csv.QUOTE_MINIMAL
• Big files → prefer csv (streaming); analysis & cleaning → pandas
👇 If this helped, like, subscribe, and comment “CSV” so I can send a cheat sheet!
#Python #CSV #Pandas #LearnToCode #Shorts