Skip to content

Instantly share code, notes, and snippets.

Created September 7, 2013 18:32
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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))
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])
print """Invalid command
Usage: python [source_file_path] [pattern] [substring]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment