#!/usr/bin/env python3 """Convert ArgyllCMS spotread TSV log to CSV, optionally adding sample labels.""" import argparse import csv import sys from pathlib import Path def load_sample_names(path: Path) -> list[str]: names = [] for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if line and not line.startswith("#"): names.append(line) return names def main() -> int: parser = argparse.ArgumentParser( description="Convert spotread TSV output to CSV with optional sample labels." ) parser.add_argument("tsv", type=Path, help="Input TSV file from spotread") parser.add_argument( "-o", "--output", type=Path, help="Output CSV path (default: same name as input)" ) parser.add_argument( "-s", "--samples", type=Path, help="Text file with one sample name per line (matched to reading order)", ) args = parser.parse_args() if not args.tsv.exists(): print(f"Error: {args.tsv} not found", file=sys.stderr) return 1 out = args.output or args.tsv.with_suffix(".csv") sample_names = load_sample_names(args.samples) if args.samples else [] with args.tsv.open(newline="", encoding="utf-8") as fin: reader = csv.reader(fin, delimiter="\t") rows = list(reader) if not rows: print("Error: empty input file", file=sys.stderr) return 1 header = rows[0] data_rows = rows[1:] if sample_names: if len(sample_names) != len(data_rows): print( f"Warning: {len(sample_names)} sample names but {len(data_rows)} readings", file=sys.stderr, ) header = ["sample_id"] + header data_rows = [ [sample_names[i] if i < len(sample_names) else f"sample_{i + 1}"] + row for i, row in enumerate(data_rows) ] with out.open("w", newline="", encoding="utf-8") as fout: writer = csv.writer(fout) writer.writerow(header) writer.writerows(data_rows) print(f"Wrote {len(data_rows)} reading(s) to {out}") return 0 if __name__ == "__main__": raise SystemExit(main())