Last active
March 10, 2020 22:20
-
-
Save SonGokussj4/af29e140e804fc86d5a3cdeb228c8b88 to your computer and use it in GitHub Desktop.
Python - replace text inplace in file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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