Skip to content

Instantly share code, notes, and snippets.

@cleverinx
Created December 11, 2018 07:10
Show Gist options
  • Save cleverinx/95a04b503df4474e799df50e6ce58dfa to your computer and use it in GitHub Desktop.
Save cleverinx/95a04b503df4474e799df50e6ce58dfa to your computer and use it in GitHub Desktop.
Multiple find and replace operations in a file at once using Python.
import re
import csv
import fileinput
replacements = {'find this' : 'replace this',
'find this too' : 'replace with this',
'find this as well' : 'also replaced',
}
lines = []
with open('input_file.csv') as infile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
print(src)
print(target)
lines.append(line)
with open('output_file.csv', 'w') as outfile:
for line in lines:
outfile.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment