Skip to content

Instantly share code, notes, and snippets.

@captainsafia
Created June 9, 2017 14:52
Show Gist options
  • Select an option

  • Save captainsafia/556cbda3aa7a9cb9020797d685d7146d to your computer and use it in GitHub Desktop.

Select an option

Save captainsafia/556cbda3aa7a9cb9020797d685d7146d to your computer and use it in GitHub Desktop.

Revisions

  1. captainsafia created this gist Jun 9, 2017.
    25 changes: 25 additions & 0 deletions replace-stdin.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    import argparse
    import csv
    import sys

    parser = argparse.ArgumentParser(description='Replace values on a column level in CSV')

    parser.add_argument('--column', help='The column to replace in', required=True)
    parser.add_argument('--search', help='The value to search for', required=True)
    parser.add_argument('--replace', help='The value to replace it with', required=True)

    args = parser.parse_args()

    data = sys.stdin.readlines()
    csv_reader = csv.reader(data)
    header = next(csv_reader)
    print(','.join(header))
    try:
    column_index = header.index(args.column)
    except ValueError as e:
    raise Exception('Column', args.column, 'not in list.')

    for row in csv_reader:
    if row[column_index] == args.search:
    row[column_index] = args.replace
    print(','.join(row))
    24 changes: 24 additions & 0 deletions replace.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    import argparse
    import csv

    parser = argparse.ArgumentParser(description='Replace values on a column level in CSV')

    parser.add_argument('--file', help='The file to read from', required=True)
    parser.add_argument('--column', help='The column to replace in', required=True)
    parser.add_argument('--search', help='The value to search for', required=True)
    parser.add_argument('--replace', help='The value to replace it with', required=True)

    args = parser.parse_args()

    with open(args.file, 'r', encoding='utf8') as data:
    csv_reader = csv.reader(data)
    header = next(csv_reader)
    try:
    column_index = header.index(args.column)
    except ValueError as e:
    raise Exception('Column', args.column, 'not in list.')

    for row in csv_reader:
    if row[column_index] == args.search:
    row[column_index] = args.replace
    print(','.join(row))