Loading...

Python CSV

A CSV table is rows of text. Each line is one row, and a comma marks the edge of a cell. The last page put one dict on one line. Here the line itself is the row. No file is opened. The rows sit in a text box in memory.

three rows in a text box

python
import csv
from io import StringIO
box = StringIO()
pen = csv.writer(box)
pen.writerow(["name", "city"])
pen.writerow(["mina", "qom"])
pen.writerow(["lida", "yazd, iran"])
print(box.getvalue(), end="")

The screen shows three lines. The first is name,city. Those are labels, not a guest. The second is mina,qom, so mina and qom are two cells. The third is lida,"yazd, iran". The quotes are there because the city itself contains a comma. end="" tells print not to add a line of its own, so the screen stops on that third line. The box already ended on a line break.

the guest and the city

python
import csv
from io import StringIO
text = "name,city\nmina,qom\nlida,\"yazd, iran\"\n"
box = StringIO(text)
rows = list(csv.reader(box))
print(rows[1][0])
print(rows[2][1])

The screen shows mina, then yazd, iran. This program starts fresh. It does not run the writer again. rows[1][0] is the first cell of the second row, the guest mina. rows[2][1] is the city. The quote marks are not part of that city. The row still has two cells. iran stays with yazd.

Cut that third line at every comma yourself, and iran looks like a third cell. The reader does not cut there. The quotes mark a single cell, and then they drop away. open and Path are not in these programs. JSON is not used. Nothing is stored in a file.

The next page is modules. This page only writes the rows and reads the cells back.

Rows, then the cells

The screen of the first program is name,city, then mina,qom, then lida,"yazd, iran". The reader then shows mina and yazd, iran. The quotes are not part of the city. No file is opened. The next page is modules.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
6
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top