Skip to content

Instantly share code, notes, and snippets.

@eenblam
Forked from captainsafia/replace-stdin.py
Last active June 11, 2017 02:39
Show Gist options
  • Save eenblam/99b5d4da0e39ed38c96b280783c121c5 to your computer and use it in GitHub Desktop.
Save eenblam/99b5d4da0e39ed38c96b280783c121c5 to your computer and use it in GitHub Desktop.
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)
parser.add_argument('data', help='The data being operated on', nargs='?',
type=argparse.FileType('r'), default=sys.stdin)
args = parser.parse_args()
csv_reader = csv.reader(args.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))
@eenblam
Copy link
Author

eenblam commented Jun 11, 2017

data.csv:

First,Second,Third
a,b,c
x,y,z

cat data.csv | replace.py --column Second --search b --replace B
and
replace.py --column Second --search b --replace B data.csv
should both produce

First,Second,Third
a,B,c
x,y,z

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment