Skip to content

Instantly share code, notes, and snippets.

@ice7mayu
Last active July 24, 2017 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ice7mayu/751529076d14b5b62c93ae5bd31e3871 to your computer and use it in GitHub Desktop.
Save ice7mayu/751529076d14b5b62c93ae5bd31e3871 to your computer and use it in GitHub Desktop.
replace text in-place within a file
import fileinput
def replace_text_in_file_demo():
"""
1. The original file is moved to a backup file
2. The standard output is redirected to the original file within the loop
3. Thus any print statements write back into the original file
"""
for line in fileinput.input('foo.txt', inplace=True, backup='.bak'):
print line.replace("foo", "bar"),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment