Use Python’s csv.DictReader when the first row contains column names, and you want to access fields by those names. Open the file withnewline="", choose an encoding that matches the export, and convert the fields you need into numbers. The CSV parser takes care of quoted commas, so an item such as “Spare bolts, zinc” stays in one field.
Make a small file to read
Save the following as orders.csv. Keep the double quotes around the first item name. They mark the comma between “bolts” and “zinc” as part of the field.
item,quantity
"Spare bolts, zinc",3
Washers,12
Save this Python program beside the CSV as read_orders.py. It uses the location of the script to find its bundled example file. If you are reading a file supplied by a command-line user, you can accept a path argument instead.
import csv
from pathlib import Path
file = Path(__file__).with_name("orders.csv")
required = {"item", "quantity"}
with file.open(encoding="utf-8-sig", newline="") as source:
rows = csv.DictReader(source, restkey=None, restval=None, strict=True)
fields = rows.fieldnames or []
if len(fields) != len(set(fields)) or not required.issubset(fields):
raise ValueError(f"Expected unique headers including {sorted(required)}")
for row in rows:
if None in row or any(value is None for value in row.values()):
raise ValueError(f"Unexpected field count near line {rows.line_num}")
item = row["item"].strip()
if not item:
raise ValueError(f"Blank item near line {rows.line_num}")
try:
quantity = int(row["quantity"])
except ValueError as error:
raise ValueError(f"Invalid quantity near line {rows.line_num}") from error
print(f"{item}: {quantity}")
Run python read_orders.py from the folder containing both files. The first line should printSpare bolts, zinc: 3, followed by Washers: 12. The colon is output formatting. The comma before “zinc” comes from the item itself.

Follow the two parts of opening the file
The newline="" option lets the CSV module handle line endings itself. It matters when fields contain line breaks inside quotes. The encoding option is a separate decision. For UTF-8 CSV exports, utf-8-sig accepts ordinary UTF-8 and strips an initial UTF-8 byte order mark, which could otherwise become part of the first header. If your export uses a different encoding, identify it at the export source and use the corresponding Python codec. Python CSV documentation
If the program reports a missing header straight away, print rows.fieldnames in a local trial. An unexpected header such as ['item;quantity'] suggests the file uses a semicolon delimiter. Confirm what the exporter wrote, then set delimiter=";" for that input. If it prints a different spelling, decide which header your tool actually accepts before adjusting the check.
Decide what counts as a broken row
The program accepts extra named columns but requires both named fields and checks for duplicate headers. A row with more fields than its header puts the extras under the None key, and missing fields receive None values. This example stops in either case. If quantity is present but empty, it is a string that fails numeric conversion. The program accepts any value Python can convert with int(), including negative integers. Add a separate range check if your orders require quantities greater than zero. Rejecting malformed rows early makes it easier to tell why an import stopped.
Try removing ,12 from the last row. It should raise an unexpected field-count error. Put the comma back but leave the quantity blank, and the program should report an invalid quantity. If a data field spans multiple physical lines, the reader’s line number counts lines read, so use it to narrow the search around the reported location.
Choose what to do with invalid data
This version stops at the first bad row, but it can already have printed earlier rows. If the destination is durable, validate before committing the input or make the writes transactional. For a one-off cleanup, you could collect invalid rows for review and continue with good rows. Keep errors visible and decide whether partially imported totals should be used. In an import that writes to a database, consider validating the entire input before any changes or using a transaction.
You can use csv.reader if the file has no headers and you know the order of its fields. For files with headings, DictReader gives names to the columns and leaves their values as text until you choose to convert them. If your next step is feeding the records into JavaScript, CyboGeek’s parsed JSON shape guide covers a related validation decision.
Separate the file path, the header, and the data
When the program fails, find out which of these it reached. A file-not-found error occurs before the CSV reader sees the header. This demo looks beside the script. Check that the two filenames match and that your editor did not silently append another extension after .csv. If you adapted the script to accept a user path, record the directory from which you launched the command. A relative path can select a different file from another terminal.
If the file opens but the first header is wrong, look at the field names the reader actually received. One long field name that includes semicolons or tabs points you toward the delimiter. A first name with an invisible prefix may indicate a byte order mark. The Python codec documentation describes how the UTF-8 signature codec handles the mark at the start of a stream. Diagnose one layer at a time rather than guessing that every problem is a broken data row.
If the header is correct, leave it in place and replace the body temporarily with one known-good row. Then add one questionable row to the copy. Now the error refers to a small file you can see clearly. Put the full export back only after you understand what the sample revealed.
Check three different kinds of blanks
A physical blank line
The dictionary reader skips empty rows. A file with a completely blank line between two data rows can still produce the two records you intended. The reader’s line number counts input lines consumed, so an error message may mention a larger number than your count of accepted records. Keep both notions separate if you add progress reporting.
An empty value in a real row
The line containing Washers followed by a comma has two fields. The second field is present but empty, and the integer conversion fails. You might decide in another project that a blank quantity means something specific, such as an unknown value. Give that choice an explicit rule if you want to accept it. A blank item name is also rejected by this fixture after trimming whitespace.
A missing field
The line containing only Washers has fewer fields than the header. The dictionary reader supplies the missing field value using its configured rest value. Here that value is None. The fixture can reject it before attempting a conversion. This is different from choosing a business default for a quantity you actually received as empty text.

Test the edges of a spreadsheet export
Keep the fixture copy and add one quoted item that contains a comma. Check that you still receive two columns. If your real export allows line breaks inside a description, test a quoted multiline value. A record can span two physical lines. Opening the text file so the CSV reader handles newlines lets the parser preserve the content marked by quotes. In a troubleshooting log, report the reader’s line number as an approximate location near the relevant record.
Next, try an export with an extra named column such as a note. This fixture permits extra names, so the record can still be read when that column is part of the header and a matching field is present. An extra value with no header is handled separately. If your real importer must accept exactly two columns, compare the full header rather than allowing any superset of the required names.

You can also put the required columns in the opposite order in a copy of the file and change the row order to match. DictReader reads each value using the name from the header, so the program should still print the same item and quantity. This is useful if a spreadsheet user can move columns around before exporting. Keep names unique, since duplicate names make a dictionary unsuitable for preserving every value under its original heading.
Decide how strict the import needs to be
Strict CSV parsing helps catch certain malformed quoting cases. Header checks and row checks handle the shape you require. A valid shape can still contain a value that makes no sense for your particular job. If your order quantity must be positive, reject zero and negative values after the integer conversion. If you instead track returns as negative amounts, include that rule so a reader knows what a minus sign represents.
A catch-and-continue tool can be useful when you need to clean a large export. Decide what you want to inspect afterward, such as the line, field, and reason for skipping. Avoid logging full rows if they contain details you do not need to share. If the import updates stock or payments, consider validating first or committing equivalent writes together so a late error does not leave only half a batch applied.
Use a broader reference when you need to write files too
The Real Python CSV walkthrough covers reading and writing with a broader set of examples. The Python CSV library reference is where to check quoting, delimiters, and dialect behaviour before changing an export and import together. If you pass data on to another tool, try exporting a known row and reading it back as part of your check.
When you have a working rule, give the next person a sample that includes the columns you expect and one realistic quoted field. Add examples of a missing and an empty quantity if your importer handles them differently. These small files document the input contract more clearly than a screenshot of a spreadsheet where the delimiter and quoting are hidden.
Keep the original export while you diagnose it
Make a copy before opening the file in a spreadsheet and saving it again. Spreadsheet software can rewrite quoting, convert values, or choose a new delimiter on export. Comparing the original with the copy lets you tell whether the parser issue was in the incoming file or appeared after the edit. When you only need to check the header and one row, a plain-text editor gives you a direct view of the quotation marks and commas Python actually receives.
Once the fixture works, try a copy of a real export and compare its header and one representative row. Quoted commas, missing fields, and blank quantities are easier to fix when the program tells you which one it found.
