How can I read a CSV file with Python’s csv module?
Quick answer
Import csv, open the file in read mode with newline='' and an explicit encoding such as utf-8, then pass it to csv.reader. Each parsed row is returned as a list. If the first row contains column names, consume it with next(reader) before looping over the remaining rows. The example reads and prints values; it does not write to the input file. [S1]
The question, the details, the next step.
A practical checklist
Replace
people.csvwith the path to your input file.Use the encoding your file is expected to have; the example requests UTF-8.
Open the file in read mode with
newline=''.Use
csv.reader(csv_file)and decide whether to consume the first row as a header.Print rows inside the
withblock; avoid write operations if you only want to read.
A few more useful answers
Does `csv.reader` return dictionaries keyed by the header names?
No. csv.reader returns each parsed row as a list. This example prints the header and rows separately; it does not map values to column names. [S1]
Will this example work with every spreadsheet export?
Not necessarily. It assumes ordinary comma-separated data, while CSV dialects can differ among applications. Check the file’s actual format if the rows do not split as expected. [S1]
Does printing rows change the CSV file?
No. The example opens the file in read mode and prints values; it does not write to the input file.
Sources
References used for this guide.
- [S1] csv — CSV file reading and writing docs.python.org · Checked
