open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello'))
Or if you want to close the file correctly:
with open('test.txt', 'r') as src: src_text = src.read() with open('test.txt', 'w') as dst: dst.write(src_text.replace('hola', 'hello'))
source share