Small, robust CSV filtering script that preserves column alignment and handles messy delimiters/encodings.
Features
- Keeps columns aligned by reading and writing with detected delimiter and quoting rules.
- Handles common delimiters (
,,;,\t,|) and falls back to a sensible default when detection fails. - Supports forcing a delimiter when automatic detection isn't correct.
- Filtering by required non-empty columns and repeatable
--whereexpressions (col=val/col!=val). - Uses
pandasfor robust text handling while preserving empty fields (no automatic NaN conversions).
Requirements
- Python 3.8+
pandas(install viapip install pandas)
Usage
Run the script from the command line:
./filter_csv.py input.csvOptions:
-o, --output: Output CSV path. Defaults to<input>_filtered.csvin same folder.--encoding: File encoding (defaultutf-8). Examples:utf-8,utf-8-sig,cp1252.--required: Comma-separated column names that must be non-empty for a row to be kept.--where: Repeatable. Filter expressions likecol=valorcol!=val(whitespace is ignored).--force-delim: Force delimiter character when detection fails (one of:,,;,\t,|). Example:--force-delim ';'.
Notes about --where and empty-check:
- Use
--where "col=val"to keep rows wherecolequalsval(exact match after trimming). - Use
--where "col!=val"to exclude rows wherecolequalsval. - To filter for empty cells, use the special values
__EMPTY__or__VIDE__. Example:--where "notes=__EMPTY__"keeps rows wherenotesis empty or only whitespace.
Examples
- Keep rows where
statusequalsactiveandemailis non-empty:
./filter_csv.py contacts.csv --required email --where "status=active"- Keep only rows where both
column1andcolumn2are non-empty:
./filter_csv.py input.csv --required column1,column2- Exclude rows where
countryequalsFrance, and write to custom output:
./filter_csv.py data.csv -o data_filtered.csv --where "country!=France"- Keep rows where
commentis empty (use the special empty token):
./filter_csv.py feedback.csv --where "comment=__EMPTY__"- If delimiter detection misfires, force semicolon delimiter:
./filter_csv.py input.csv --force-delim ';'Behavior details
- The script attempts to auto-detect the CSV dialect (delimiter, quotechar, etc.) using Python's
csv.Snifferon a sample. If detection fails it falls back to;as delimiter. - Files are read with
pandas.read_csv(..., dtype='string', keep_default_na=False)to preserve empty fields as empty strings rather than NaN. - Output uses the detected delimiter and conservative quoting to keep columns aligned even for tricky cell contents.
License
I don't care, do whatever you want.