user2487593
user2487593

Reputation: 53

Search and replace line in Python text stream

I'm trying to parse a text stream in Python. The contents are being checked line-by-line and, when matched, the given line is passed to a function for processing.

The processing is working and the function returns the expected results. However, I've been unable to update the original stream with the new line--the intent is to replace the matched line with the 'text' value that the function returns.

The code I use for this is as follows:

import StringIO
for line in StringIO.StringIO(data):
  if line.startswith('MATCHTHIS'):
    meta, text = parse_data(line)

Everything works up until this point--that is, 'meta' and 'text' contain the values I expect. But I'm unable to update the specific line in 'data' to reflect the value of 'text'.

line.replace(line, text) works within the if block but the change doesn't make it back to 'data'.

Upvotes: 1

Views: 1710

Answers (1)

BoppreH
BoppreH

Reputation: 10173

Strings are immutable objects in you Python, you can't change their values. If you want to change the value inside the StringIO buffer, you can do so as with any other file using seek and write, but replacing lines with different lengths will be a problem.

I suggest modeling the text stream as a list of lines. Ex:

text = "line 1\nMATCHTHIS line 2\nline 3"
lines = text.split('\n')

for i, line in enumerate(lines):
    if line.startswith("MATCHTHIS"):
        meta, new_line = parse_data(line)
        lines[i] = new_line # Replace old line.

 new_text = '\n'.join(lines) # Recreate text with replaced lines.

Also, classic console tools like sed and piping are perfect for this job.

Upvotes: 2

Related Questions