I'm new to Python. I want to be able to open a file and replace every instance of certain words with a given replacement via Python. as an example say replace every word 'zero' with '0', 'temp' with 'bob', and say 'garbage' with 'nothing'.
I had first started to use this:
for line in fileinput.input(fin): fout.write(line.replace('zero', '0')) fout.write(line.replace('temp','bob')) fout.write(line.replace('garbage','nothing'))
but I don't think this is an even remotely correct way to do this. I then thought about doing if statements to check if the line contains these items and if it does, then replace which one the line contains, but from what I know of Python this also isn't truly an ideal solution. I would love to know what the best way to do this. Thanks ahead of time!
To replace text in a file we are going to open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions.
This should do it
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'} with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile: for line in infile: for src, target in replacements.items(): line = line.replace(src, target) outfile.write(line)
EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:
lines = [] with open('path/to/input/file') as infile: for line in infile: for src, target in replacements.items(): line = line.replace(src, target) lines.append(line) with open('path/to/input/file', 'w') as outfile: for line in lines: outfile.write(line)
Edit: If you are using Python 2.x, use replacements.iteritems()
instead of replacements.items()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With