Skip to content

Instantly share code, notes, and snippets.

@kirang89
Created September 7, 2013 18:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kirang89/6478017 to your computer and use it in GitHub Desktop.
Save kirang89/6478017 to your computer and use it in GitHub Desktop.
Simple, clean way of replacing lines in a file
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from tempfile import mkstemp
from shutil import move
from os import remove
import sys
def replace(source_file_path, pattern, substring):
fh, target_file_path = mkstemp()
with open(target_file_path, 'w') as target_file:
with open(source_file_path, 'r') as source_file:
for line in source_file:
target_file.write(line.replace(pattern, substring))
remove(source_file_path)
move(target_file_path, source_file_path)
if __name__ == '__main__':
if len(sys.argv) == 4:
replace(sys.argv[1], sys.argv[2], sys.argv[3])
else:
print """Invalid command
Usage: python replacelinesinfile.py [source_file_path] [pattern] [substring]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment