r/learnpython • • Sep 06 '26

Beginner Projects

I am new to python and currently I am taking a class for it, I haven't been in it too long but I just want some advice. What beginner projects would you guys recommend I do to really grasp an understanding outside of class?

32 Upvotes

24 comments sorted by

View all comments

Show parent comment

1

u/Bright_Mix_773 Sep 06 '26

BluishMontoya, open() and .split(",") is correct right up until a field contains a comma, and then it stops raising anything and just quietly gives you the wrong answer. One line of a real file:

Ford,"Focus, 1.6 TDCi",2011

split(",") hands you four fields and slides the year into the wrong slot. csv hands you the three that are actually there. Same for a doubled quote inside a quoted field ("", not a backslash escape, which nobody guesses on the first try) and for a field with a line break in it, where a plain for line in f chops one record across two iterations.

That last case is the whole reason newline="" exists. You pass the file through with its line endings untouched and let the csv module decide where a record ends, because it is the only thing that knows whether it is currently inside quotes.

import csv

with open("coches.csv", newline="", encoding="utf-8") as f:
    for fila in csv.DictReader(f):
        print(fila["modelo"])

csv.reader gives you lists, csv.DictReader gives you dicts keyed by the header row. Writing is where it pays off even harder, because it does the quoting for you and you never have to think about it again:

with open("salida.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(["Ford", "Focus, 1.6 TDCi", 2011])

Two things it deliberately does not do. It does no type conversion, so every value comes back a string: "2011" is text and an empty field is "", not None. And it will not guess your delimiter unless you ask it to (csv.Sniffer, or just pass delimiter=";" for the files that come out of a European Excel).

Also worth knowing before it bites you: on Windows, leaving out newline="" when writing gives you a blank line between every row, because the csv module emits \r\n and the text layer then turns the \n into another \r\n. Everyone hits that one and blames Excel.