When you think you need to look ahead, it is almost always simpler to restate the problem in terms of looking back. In this case, just keep track of the previous line and look at that to see if it matches your target string.
infilename = "problematic.txt"
outfilename = "resolved.txt"
pattern = "xxx"
replace1 = "something"
replace2 = "stg"
with open(infilename) as infile:
with open(outfilename, "w") as outfile:
previous = ""
for linenum, current in enumerate(infile):
if pattern in previous:
print "found at line", linenum
previous, current = replace1, replace2
if linenum: # skip the first (blank) previous line
outfile.write(previous)
previous = current
outfile.write(previous) # write the final line