β What is CSV?
Think of a CSV file like an Excel sheet, but instead of rows and columns, it uses commas to separate the values.
πΉ Example content of a CSV file:
Name,Age
Ravi,22
Amit,20Each row represents a record (like a student).
Each column has a field (like name or age).
.csvfiles are great for tabular data like attendance, marks, sales, etc.
π Reading a CSV File in Python
import csv
with open('students.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)β Explanation:
import csvβ We use Python's built-incsvmodule.open(..., 'r')β Open the file in read mode.csv.reader(...)β Helps us read the file row by row.for row in reader:β Eachrowis a list of values like['Ravi', '22'].
π¦ Output on screen:
['Name', 'Age']
['Ravi', '22']
['Amit', '20']βοΈ Writing to a CSV File
import csv
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"]) # Header
writer.writerow(["Ravi", 22]) # Row 1
writer.writerow(["Tisha", 20]) # Row 2β Explanation:
open(..., 'w')β Write mode (overwrites the file if it exists).newline=''β Prevents blank lines between rows (especially on Windows).writerow([...])β Writes a single row of data.
π Whatβs inside output.csv now?
Name,Age
Ravi,22
Amit,20π Real-Life Use Cases for CSV:
Storing student marks or attendance.
Exporting product lists from a shop.
Downloading data from a website or app in table form.
β What is JSON?
JSON is like a dictionary in Python.
It stores data as key-value pairs (just like contacts in your phone: name β number).
Itβs widely used in web development, APIs, and data sharing between apps.
βοΈ Saving (Writing) JSON Data
import json
person = {"name": "Alice", "age": 25}
with open("data.json", "w") as f:
json.dump(person, f)β Explanation:
json.dump(...)converts Python data into JSON format and saves it in a file.The file
data.jsonwill look like this:
{"name": "Alice", "age": 25}π Reading JSON Data
import json
with open("data.json") as f:
data = json.load(f)
print(data){'name': 'Alice', 'age': 25}json.load(...)reads the JSON file and converts it back to a Python dictionary.
<div class="infographic-pycsvjson">
<style>
.infographic-pycsvjson {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--err: #c0392b; --err-soft: #fbe9e7;
--ok: #1f9d55; --ok-soft: #e3f5ec;
--mono-font: 'IBM Plex Mono', 'SFMono-Regular', Menlo, monospace;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', system-ui, sans-serif;
box-sizing: border-box;
max-width: 740px;
margin: 0 auto;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-pycsvjson[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--err: #e57373; --err-soft: #3a2222;
--ok: #6fdc8c; --ok-soft: #16342a;
}
.infographic-pycsvjson *, .infographic-pycsvjson *::before, .infographic-pycsvjson *::after { box-sizing: border-box; }
.infographic-pycsvjson .cj-wrap { padding: 0 clamp(1rem, 4vw, 2rem) 1.5rem; }
.infographic-pycsvjson h1 {
font-family: var(--display-font); font-weight: 600;
font-size: clamp(1.45rem, 5vw, 1.95rem); text-align: center; margin: 1.5rem 0 0.25rem; letter-spacing: -0.01em;
}
.infographic-pycsvjson .cj-sub { text-align: center; color: var(--ink-soft); font-size: 0.85rem; margin: 0 0 1.3rem; }
.infographic-pycsvjson .cj-tabs { display: flex; justify-content: center; gap: 0.35rem; margin-bottom: 1.4rem; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
.infographic-pycsvjson .cj-tab-btn {
font: inherit; font-family: var(--mono-font); font-size: 0.82rem; font-weight: 700;
background: none; border: none; border-bottom: 2.5px solid transparent; color: var(--ink-soft);
padding: 0.55rem 0.85rem; cursor: pointer; margin-bottom: -1px;
}
.infographic-pycsvjson .cj-tab-btn.is-active { color: var(--accent); border-bottom-color: var(--accent); }
.infographic-pycsvjson .cj-panel.is-hidden-tab { display: none; }
.infographic-pycsvjson .raw-textarea {
width: 100%; font-family: var(--mono-font); font-size: 0.82rem; padding: 0.6rem 0.7rem;
border: 1.5px solid var(--line); border-radius: 8px; background: var(--paper-alt); color: var(--ink);
resize: vertical; min-height: 5.5em; margin-bottom: 0.8rem;
}
.infographic-pycsvjson .raw-textarea:focus { outline: none; border-color: var(--accent); }
.infographic-pycsvjson .btn-row { display: flex; justify-content: center; gap: 0.4rem; margin-bottom: 0.9rem; flex-wrap: wrap; }
.infographic-pycsvjson .btn {
font: inherit; font-family: var(--mono-font); font-size: 0.78rem; font-weight: 700;
background: var(--accent); color: #fff; border: none; border-radius: 999px;
padding: 0.42rem 0.85rem; cursor: pointer;
}
.infographic-pycsvjson .btn.secondary { background: var(--paper-alt); color: var(--ink); border: 1.5px solid var(--line); border-radius: 6px; }
.infographic-pycsvjson .write-row { display: flex; justify-content: center; gap: 0.4rem; margin-bottom: 0.9rem; flex-wrap: wrap; }
.infographic-pycsvjson .write-row input {
font-family: var(--mono-font); font-size: 0.8rem; padding: 0.35rem 0.55rem;
border: 1.5px solid var(--line); border-radius: 5px; background: var(--paper-alt); color: var(--ink); width: 100px;
text-align: center;
}
.infographic-pycsvjson .write-row input:focus { outline: none; border-color: var(--accent); }
.infographic-pycsvjson .result-table { width: 100%; border-collapse: collapse; font-family: var(--mono-font); font-size: 0.78rem; margin-bottom: 0.9rem; }
.infographic-pycsvjson .result-table th, .infographic-pycsvjson .result-table td {
border: 1px solid var(--line); padding: 0.35rem 0.55rem; text-align: left;
}
.infographic-pycsvjson .result-table th { background: var(--paper-alt); color: var(--ink-soft); }
.infographic-pycsvjson .dict-cards { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: center; margin-bottom: 0.9rem; }
.infographic-pycsvjson .dict-card {
border: 1.5px solid var(--accent); background: var(--accent-soft); border-radius: 8px; padding: 0.5rem 0.7rem;
font-family: var(--mono-font); font-size: 0.74rem;
}
.infographic-pycsvjson .dict-card div { margin-bottom: 0.12rem; }
.infographic-pycsvjson .dict-card b { color: var(--accent); }
.infographic-pycsvjson .device {
--ed-bg: #1e1e1e; --ed-bar: #2d2d2d; --ed-text: #d4d4d4; --ed-soft: #8a8a8a; --ed-ok: #6fdc8c; --ed-err: #ff6b6b;
background: var(--ed-bg); border: 1px solid var(--line); border-radius: 8px; overflow: hidden;
}
.infographic-pycsvjson .device-bar {
display: flex; align-items: center; gap: 0.4rem;
background: var(--ed-bar); padding: 0.5rem 0.7rem; border-bottom: 1px solid #3a3a3a;
font-size: 0.72rem; color: var(--ed-soft); font-weight: 600;
}
.infographic-pycsvjson .device-bar .dot { width: 9px; height: 9px; border-radius: 50%; background: #5a5a5a; }
.infographic-pycsvjson .device-bar .dot:nth-child(1) { background: #ff5f56; }
.infographic-pycsvjson .device-body { padding: 0.75rem 0.9rem; font-family: var(--mono-font); font-size: 0.78rem; color: var(--ed-text); min-height: 60px; max-height: 220px; overflow-y: auto; white-space: pre-wrap; }
.infographic-pycsvjson .log-line { line-height: 1.6; opacity: 0; animation: cj-fadein 0.2s ease forwards; }
@keyframes cj-fadein { from { opacity: 0; } to { opacity: 1; } }
.infographic-pycsvjson .log-line.cmd { color: var(--ed-ok); font-weight: 700; margin-top: 0.4rem; }
.infographic-pycsvjson .log-line.cmd:first-child { margin-top: 0; }
.infographic-pycsvjson .log-line.err { color: var(--ed-err); }
.infographic-pycsvjson .log-empty { color: var(--ed-soft); }
.infographic-pycsvjson .cj-caption { text-align: center; font-size: 0.85rem; color: var(--ink-soft); margin-top: 0.9rem; }
@media (prefers-reduced-motion: reduce) {
.infographic-pycsvjson *, .infographic-pycsvjson *::before, .infographic-pycsvjson *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="cj-wrap">
<h1>Working with CSV & JSON</h1>
<p class="cj-sub">CSV is rows and columns. JSON is nested keys and values. Both round-trip to plain Python.</p>
<div class="cj-tabs">
<button class="cj-tab-btn is-active" data-tab="csv">CSV</button>
<button class="cj-tab-btn" data-tab="json">JSON</button>
</div>
<!-- CSV TAB -->
<div class="cj-panel" id="tabCsv">
<textarea class="raw-textarea" id="csvText">name,age,city
Alice,25,NYC
Bob,30,LA</textarea>
<div class="btn-row">
<button class="btn" id="csvReaderBtn">csv.reader(f)</button>
<button class="btn" id="csvDictReaderBtn">csv.DictReader(f)</button>
</div>
<div class="write-row">
<input id="csvNewName" type="text" value="Chen" placeholder="name" />
<input id="csvNewAge" type="text" value="28" placeholder="age" />
<input id="csvNewCity" type="text" value="SF" placeholder="city" />
<button class="btn secondary" id="csvWriteBtn">writer.writerow([...])</button>
</div>
<div id="csvResultArea"></div>
<div class="device">
<div class="device-bar"><span class="dot"></span><span class="dot"></span><span class="dot"></span> Terminal</div>
<div class="device-body" id="csvLog"><div class="log-empty">Try reading the CSV above, or add a new row to it.</div></div>
</div>
<p class="cj-caption">reader() gives plain lists. DictReader() uses the header row as keys β same data, friendlier shape.</p>
</div>
<!-- JSON TAB -->
<div class="cj-panel is-hidden-tab" id="tabJson">
<textarea class="raw-textarea" id="jsonText">{"name": "Alice", "age": 25, "hobbies": ["reading", "chess"]}</textarea>
<div class="btn-row">
<button class="btn" id="jsonLoadsBtn">json.loads(text)</button>
<button class="btn secondary" id="jsonDumpsBtn">json.dumps(data, indent=2)</button>
</div>
<div class="device">
<div class="device-bar"><span class="dot"></span><span class="dot"></span><span class="dot"></span> Terminal</div>
<div class="device-body" id="jsonLog"><div class="log-empty">Parse the JSON above into a Python object, then dump it back out.</div></div>
</div>
<p class="cj-caption">loads() turns JSON text into a real Python dict/list. dumps() turns it back into text.</p>
</div>
</div>
<script>
(function () {
var root = document.currentScript.closest('.infographic-pycsvjson')
|| document.querySelector('.infographic-pycsvjson');
var bodyAttr = document.body.getAttribute('data-darkmode');
var dark;
if (bodyAttr === 'true') { dark = true; }
else if (bodyAttr === 'false') { dark = false; }
else {
var match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) root.setAttribute('data-theme', 'dark');
/* ---------------- tabs ---------------- */
var tabBtns = root.querySelectorAll('.cj-tab-btn');
var panels = { csv: root.querySelector('#tabCsv'), json: root.querySelector('#tabJson') };
tabBtns.forEach(function (btn) {
btn.addEventListener('click', function () {
tabBtns.forEach(function (b) { b.classList.toggle('is-active', b === btn); });
var target = btn.dataset.tab;
Object.keys(panels).forEach(function (key) {
panels[key].classList.toggle('is-hidden-tab', key !== target);
});
});
});
/* ================= CSV ================= */
var csvText = root.querySelector('#csvText');
var csvResultArea = root.querySelector('#csvResultArea');
var csvLog = root.querySelector('#csvLog');
var csvFirstLog = true;
function parseCsv(text) {
return text.split('\n').map(function (line) { return line.trim(); })
.filter(function (line) { return line.length > 0; })
.map(function (line) { return line.split(',').map(function (c) { return c.trim(); }); });
}
function logCsv(text, cls) {
if (csvFirstLog) { csvLog.innerHTML = ''; csvFirstLog = false; }
var line = document.createElement('div');
line.className = 'log-line' + (cls ? ' ' + cls : '');
line.textContent = text;
csvLog.appendChild(line);
csvLog.scrollTop = csvLog.scrollHeight;
}
root.querySelector('#csvReaderBtn').addEventListener('click', function () {
var rows = parseCsv(csvText.value);
logCsv('for row in csv.reader(f): print(row)', 'cmd');
rows.forEach(function (r) { logCsv('[' + r.map(function (c) { return "'" + c + "'"; }).join(', ') + ']'); });
var table = document.createElement('table');
table.className = 'result-table';
rows.forEach(function (r, i) {
var tr = document.createElement('tr');
r.forEach(function (cell) {
var el = document.createElement(i === 0 ? 'th' : 'td');
el.textContent = cell;
tr.appendChild(el);
});
table.appendChild(tr);
});
csvResultArea.innerHTML = '';
csvResultArea.appendChild(table);
});
root.querySelector('#csvDictReaderBtn').addEventListener('click', function () {
var rows = parseCsv(csvText.value);
if (rows.length < 1) return;
var header = rows[0];
var dicts = rows.slice(1).map(function (r) {
var obj = {};
header.forEach(function (h, i) { obj[h] = r[i]; });
return obj;
});
logCsv('for row in csv.DictReader(f): print(row)', 'cmd');
dicts.forEach(function (d) {
logCsv('{' + Object.keys(d).map(function (k) { return "'" + k + "': '" + d[k] + "'"; }).join(', ') + '}');
});
var wrap = document.createElement('div');
wrap.className = 'dict-cards';
dicts.forEach(function (d) {
var card = document.createElement('div');
card.className = 'dict-card';
card.innerHTML = Object.keys(d).map(function (k) { return '<div><b>' + k + ':</b> ' + d[k] + '</div>'; }).join('');
wrap.appendChild(card);
});
csvResultArea.innerHTML = '';
csvResultArea.appendChild(wrap);
});
root.querySelector('#csvWriteBtn').addEventListener('click', function () {
var name = root.querySelector('#csvNewName').value.trim() || 'Chen';
var age = root.querySelector('#csvNewAge').value.trim() || '28';
var city = root.querySelector('#csvNewCity').value.trim() || 'SF';
var newRow = name + ',' + age + ',' + city;
csvText.value = csvText.value.replace(/\n*$/, '') + '\n' + newRow;
logCsv('writer.writerow(["' + name + '", "' + age + '", "' + city + '"])', 'cmd');
logCsv('β appended as a new line in the CSV above');
});
/* ================= JSON ================= */
var jsonText = root.querySelector('#jsonText');
var jsonLog = root.querySelector('#jsonLog');
var jsonFirstLog = true;
var parsedData = null;
function logJson(text, cls) {
if (jsonFirstLog) { jsonLog.innerHTML = ''; jsonFirstLog = false; }
var line = document.createElement('div');
line.className = 'log-line' + (cls ? ' ' + cls : '');
line.textContent = text;
jsonLog.appendChild(line);
jsonLog.scrollTop = jsonLog.scrollHeight;
}
function pyRepr(v, indent) {
indent = indent || 0;
if (v === null) return 'None';
if (v === true) return 'True';
if (v === false) return 'False';
if (typeof v === 'number') return String(v);
if (typeof v === 'string') return "'" + v + "'";
if (Array.isArray(v)) return '[' + v.map(function (x) { return pyRepr(x); }).join(', ') + ']';
if (typeof v === 'object') {
return '{' + Object.keys(v).map(function (k) { return "'" + k + "': " + pyRepr(v[k]); }).join(', ') + '}';
}
return String(v);
}
root.querySelector('#jsonLoadsBtn').addEventListener('click', function () {
logJson('data = json.loads(text)', 'cmd');
try {
parsedData = JSON.parse(jsonText.value);
logJson('print(data)');
logJson(pyRepr(parsedData));
} catch (e) {
parsedData = null;
logJson('json.decoder.JSONDecodeError: ' + e.message, 'err');
}
});
root.querySelector('#jsonDumpsBtn').addEventListener('click', function () {
logJson('print(json.dumps(data, indent=2))', 'cmd');
if (parsedData === null) {
logJson('NameError: name \'data\' is not defined β run json.loads first', 'err');
return;
}
var pretty = JSON.stringify(parsedData, null, 2);
pretty.split('\n').forEach(function (line) { logJson(line); });
});
})();
</script>
</div>π Real-Life Use Cases for JSON:
Storing user settings (like dark mode on/off).
Handling API data from websites (like weather, news, etc.).
Saving configuration data in applications.
π§ When to Use What?
Feature | CSV | JSON |
|---|---|---|
Structure | Rows and columns (tabular) | Nested data (like a dictionary) |
Best For | Simple tables (e.g., marks) | Structured data (e.g., user info) |
Human-readable | β Yes | β Yes |
Supported By Excel | β Yes | β Not directly |
Use in APIs | β No | β Yes |
π§ Summary:
Use CSV when data looks like a table.
Use JSON when data looks like key-value pairs or nested objects.
Always use
with open(...)β it's safer and auto-closes the file!