Skip to content Skip to sidebar Skip to footer

Python: Search For A Str1 In A Line And Replace The Whole Line With Str2

I have a file in which I need to search for STR1 and replace the whole line containing STR2. For example the file1 contains the following data Name: John Height: 6.0 Weight: 190 Ey

Solution 1:

You can use string.find() to determine if a string is within another string. Related Python docs.

#! /usr/bin/pythonimport fileinput
for line in fileinput.input("file1", inplace=True):
    if line.find("Name:") >= 0:
        print"Name: Robert"else:
        print line[:-1]

Solution 2:

Should do exactly what you want.

def replace_basic(key_to_replace, new_value, file):
    f = open(file, 'rb').readlines()
    with open(file, 'wb') asout:
        for line in f:
            if key_to_replace in line:
                out.write(new_value+'/n') #asuming that your format never changes then uncomment the next line and comment outthis one.
                #out.write('{}: {}'.format(key_to_replace, new_value))
                continueout.write(line)

Post a Comment for "Python: Search For A Str1 In A Line And Replace The Whole Line With Str2"