Skip to content

Instantly share code, notes, and snippets.

@tshrinivasan
Last active December 10, 2020 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tshrinivasan/8e474e4c4b9dc69a4056b525f994b4e7 to your computer and use it in GitHub Desktop.
Save tshrinivasan/8e474e4c4b9dc69a4056b525f994b4e7 to your computer and use it in GitHub Desktop.
python script to replace multiple strings from a given csv file
# sample content of replace_dictionary.csv
#gooood, god
#baaaad, bad
#coool, cool
#
replace_dict = {}
dict_file = open('replace_dictionary.csv','r',encoding="utf8")
for line in dict_file:
find = line.split(',')[0].strip()
replace = line.split(',')[1].strip()
replace_dict[find] = replace
def replace_content(line, dictionary):
for item in dictionary:
if item in line:
line = line.replace(item, dictionary[item])
return line
in_file = open('input.txt', 'r',encoding="utf8")
out_file = open('output.txt', 'w',encoding="utf8")
for line in in_file:
out_file.write(replace_content(line, replace_dict))
in_file.close()
out_file.close()
print("replaced the contents. check the file output.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment