SOP for validating xSV files #4196
Replies: 2 comments
|
Short answer: I don't think there is currently a single
For a generic xSV preflight, I would therefore split with a CSV-aware reader before passing import csv
import json
with (
open("input.tsv", newline="", encoding="utf-8-sig") as src,
open("valid.tsv", "w", newline="", encoding="utf-8") as valid,
open("errors.tsv", "w", newline="", encoding="utf-8") as errors,
):
reader = csv.reader(src, delimiter="\t")
good = csv.writer(valid, delimiter="\t")
bad = csv.writer(errors, delimiter="\t")
header = next(reader)
expected = len(header)
good.writerow(header)
bad.writerow(["record", "expected_fields", "actual_fields", "row_json"])
for record_number, row in enumerate(reader, 2):
if len(row) == expected:
good.writerow(row)
else:
bad.writerow(
[record_number, expected, len(row), json.dumps(row, ensure_ascii=False)]
)That preserves quoted tabs and quoted multiline fields correctly. The If the input contract guarantees no quoting, embedded tabs, or embedded newlines, then the simpler line-oriented version is fine: awk -F '\t' '
NR == 1 { n = NF; print > "valid.tsv"; next }
NF == n { print > "valid.tsv"; next }
{ print > "errors.tsv" }
' input.tsvI would not use that So my SOP would be: structural quarantine first with a CSV-aware reader, then run |
|
Thanks @Samielakkad for jumping in. Adding the feature to |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I'm putting together a generic xSV validation script that uses various qsv commands, and was wondering whether there were best practices around dealing with files that have missing or extra columns in some rows. I know about
fixlengths, but I would prefer to just remove the erroneous lines for human attention instead of potentially messing up the data for a row and sending that dodgy data on for further processing.Since the file I'm dealing with is TSV, the easiest approach is to use a command line tool (e.g. sed, awk) to pick out lines with the incorrect number of tabs and send them to an
errors.tsvfile and the other lines tovalid.tsv.fixlengthsand do something involving diffing the file against the original, but that seems convoluted / inelegant.All reactions