Skip to content

Instantly share code, notes, and snippets.

@SonGokussj4
Last active March 10, 2020 22:20
Show Gist options
  • Save SonGokussj4/af29e140e804fc86d5a3cdeb228c8b88 to your computer and use it in GitHub Desktop.
Save SonGokussj4/af29e140e804fc86d5a3cdeb228c8b88 to your computer and use it in GitHub Desktop.
Python - replace text inplace in file
# cat $HOME/my_file.txt
# Hi there
# This is a second line
# And third with text_to_replace string
import fileinput
from pathlib import Path
filepath = Path.home() / my_file.txt
with fileinput.FileInput(str(filepath.resolve()), inplace=True) as f:
for line in f:
print(line.replace('text_to_replace', "replaced_text"), end='')
# cat $HOME/my_file.txt
# Hi there
# This is a second line
# And third with replaced_text string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment