Hand-built CSV strings break as soon as a value contains a comma or quote; the writer never does.
csv.writer(f) wraps a file opened for writing (again with newline=""). Then:
writer.writerow(["Ada", 36, "London, UK"])writes one record,writer.writerows(rows)writes any iterable of rows, including a generator.
The writer converts non-string values with str(), writes None as an empty string, and quotes fields only when needed (QUOTE_MINIMAL): fields containing the delimiter, the quote character or a newline are wrapped in quotes, and embedded quotes are doubled.
Lines end with \r\n by default, which is what the CSV specification (RFC 4180) and Excel expect. That's why newline="" matters when writing too: on Windows, without it, Python would translate the \n into \r\n again, producing \r\r\n and blank rows between records in Excel.
Floats are written with repr, so 0.1 + 0.2 becomes 0.30000000000000004. Round or format numbers yourself if the file is for humans: f"{price:.2f}".
Use mode="a" to append rows to an existing file, but only write the header when the file is new.
Example
import csv
rows = [
["name", "age", "address", "note"],
["Ada", 36, "London, UK", 'says "hi" once'],
["Linus", None, "Helsinki", 0.1 + 0.2],
]
with open("out.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(rows)
print(repr(open("out.csv", newline="").read()))
# 'name,age,address,note\r\nAda,36,"London, UK","says ""hi"" once"\r\n'
# 'Linus,,Helsinki,0.30000000000000004\r\n' (one string, shown split)Remember
- csv.writer + writerow/writerows; open with newline=''
- Quoting and escaping are automatic
- None becomes an empty field; other values use str()
Watch out for
- Opening the output file without newline='' on Windows, producing blank lines between rows.