Handle comments in CSV files
How comment lines in CSV and TSV files behave, which readers skip them, where they cause problems, and when to keep notes outside the data instead.
Comment lines are a common way to attach notes to a CSV or TSV file: an export date, a source description, a warning about units. They are also a common reason a file loads differently in one program than in another. This review explains what adding or stripping comments changes in a file, where the results stay usable, and when plain, comment-free data is the safer choice.
Short answer: are CSV comments suitable for your use?
Comments are reasonable when the file stays inside a pipeline you control and every reader in that pipeline is configured to skip them. The benefit is that notes travel with the data in one file. The deciding tradeoff is that comments are not part of the commonly cited CSV specification (RFC 4180), so any reader that is not told about them will treat them as data rows.
Plain, comment-free CSV is the better choice when the file will be shared with people or systems you do not control, opened in a spreadsheet, loaded into a database, or validated against a strict schema. In those cases, keep the notes in a separate file or a documented metadata format.
What a comment convention actually changes
A CSV comment changes stored characters, not presentation. A line beginning with a marker, most often #, is written into the file like any other line. Nothing in the file itself marks it as special. Whether it is a comment depends entirely on the program reading it and how that program is configured.
That makes "handling comments" mean one of two different operations, and it helps to know which one a tool performs:
- Skipping at read time: the parser ignores comment lines while loading, and the file on disk is unchanged.
- Stripping as a transformation: a tool writes a new file without the comment lines, so the notes are removed from the stored text.
Readers also differ in how far a comment extends. Some only ignore lines that begin with the marker. Others treat the marker as "ignore the rest of this line" wherever it appears, so it can cut off the end of a data row. The pandas read_csv function, for example, documents its comment parameter as indicating that the remainder of the line should not be parsed. Python's standard csv module has no comment option at all, so comment lines come through as ordinary rows unless you filter them first.
Defaults vary as well. In R, read.table treats # as a comment character by default, while read.csv sets the comment character to empty, so the same file can load differently depending on which function is called. Check the documentation of the exact reader and version you use rather than assuming a shared convention.
A worked example and where it can go wrong
# Source: quarterly export
# Units: amounts in USD
id,name,note
1,Ada,"tagged #urgent"
2,Lin,"line one
# not a comment, still inside the quoted field"
3,Sam,plain
The first two lines are intended as comments. Rows 1 and 2 show the two main risks.
- Row 1 has a # inside a quoted field. A reader that treats # as "ignore the rest of the line" may truncate the note, depending on whether it honors quotes before looking for comments. Test your reader with this case.
- Row 2 has a quoted field that spans two physical lines, and the second line starts with #. A naive filter that drops every line starting with # before parsing will delete part of the field and leave an unclosed quote, which can shift or corrupt later rows.
- Row 3 is unaffected in any common approach.
No tool output for this example was supplied or tested here. Treat it as a test file to run through your own reader, not as a statement of how a particular program behaves.
If you strip comments yourself, filtering whole lines is only safe when your data never contains multi-line quoted fields. A cautious pattern in Python is to drop leading comment lines only, before the header:
import csv
with open("data.csv", newline="", encoding="utf-8") as f:
lines = iter(f)
for line in lines:
if not line.startswith("#"):
break
rows = csv.reader([line], ) if False else None
reader = csv.reader(__import__("itertools").chain([line], lines))
for row in reader:
print(row)
A clearer version of the same idea, which only skips the comment block at the top and leaves anything after the header to the CSV parser:
import csv
import itertools
with open("data.csv", newline="", encoding="utf-8") as f:
body = itertools.dropwhile(lambda line: line.startswith("#"), f)
for row in csv.reader(body):
print(row)
This keeps quoted fields intact because the csv module, not a line filter, decides where records end. It does not remove comments placed between data rows; if your files have those, you need a reader that supports comments natively or a convention that forbids them.
Will the file stay readable and usable after sharing?
Readability for people and usability for software pull in different directions here.
- Spreadsheets: when a commented file is opened directly, comment lines generally appear as ordinary rows above or among the data. The notes stay visible, but the header may no longer be the first row, and sorting or filtering can mix comments into the data.
- Databases and import wizards: comment lines are usually read as records or rejected as malformed, unless the import tool offers a skip-rows or comment setting.
- Schema validation: a strict validator will typically flag comment lines because their column count does not match the header.
- Copy and paste: copying the file's text preserves comment lines exactly, since they are ordinary characters. Pasting into a spreadsheet or form gives the same results as opening the file.
- Search and editing: comments remain searchable as plain text, which is useful, but a find-and-replace across the file can alter them as easily as data.
Accessibility depends on where the file ends up. If comment lines become rows in a spreadsheet, a screen reader user may encounter them as table cells and lose track of which row is the real header. No documentation or tests for specific assistive technologies were supplied, so this is a structural concern rather than a verified result for any particular screen reader. A comment-free table with a single header row is the more predictable structure.
Options compared
| Approach | Notes stay with data | Works in unconfigured readers | Main risk |
| Comment lines in the CSV | Yes | No, appear as data | Misparsed rows, truncated fields |
| Skip comments at read time | Yes, file unchanged | Only in readers configured for it | Inconsistent results across tools |
| Strip comments before sharing | No, notes removed | Yes | Information loss unless saved elsewhere |
| Separate notes or metadata file | In a companion file | Yes | Files can be separated or fall out of sync |
Some tabular metadata standards, such as the W3C CSV on the Web vocabulary and Frictionless table dialect descriptions, let you declare a comment marker alongside the file so compatible tools know to skip it. That helps only with tools that read the metadata; other programs will still see plain lines.
When to keep the data plain
- The file goes to an outside system, a client, or a public dataset.
- It will be opened in a spreadsheet by people who did not create it.
- It feeds a database import, an API, or a schema validator.
- The data may contain # or your chosen marker inside fields.
- Fields can span multiple lines and you cannot confirm your reader handles comments safely.
In those situations, strip the comments, save the notes in a README or metadata file next to the CSV, and keep a single header row. If you control every reader, comments can work, as long as each reader's comment setting is documented and tested on a sample containing the marker inside quoted and multi-line fields.
Gaps in this review
No tool-specific evidence was supplied: no test outputs, version numbers, or documentation excerpts for particular spreadsheets, converters, or assistive technologies. Statements about named libraries reflect their general documented behavior and should be checked against the version you use. Privacy and data-handling practices of any online CSV tool were not assessed and should not be inferred from its interface.