Search and replace text in a file #
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as f:
for line in f:
print(line.replace(text_to_search, replacement_text), end='')
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as f:
for line in f:
print(line.replace(text_to_search, replacement_text), end='')
Append to a file #
#!/usr/bin/env python3
with open("test.txt", "a") as f:
f.write("appended text")
with open("test.txt", "a") as f:
f.write("appended text")
Show Comments