Q:

Python 2.7 - Read text replace and write to same file

I am reading a text file ( 20 + lines) and doing a find and replace at multiple places in the text with the below code .
with open(r"c:\TestFolder\test_file_with_State.txt","r+") as fp:
    finds = 'MI'
    pattern = re.compile(r'[,\s]+' + re.escape(finds) + r'[\s]+')
    textdata = fp.read()
    line = re.sub(pattern,'MICHIGAN',textdata)
    fp.write(line)

When trying to write it back to the same file, I get the below error.
IOError                                   Traceback (most recent call last)
<ipython-input> in <module>()
      6     line = re.sub(pattern,'MICHIGAN',textdata)
      7     print line
----> 8     fp.write(line)
      9 

what is that I am doing wrong.

A:

You've already read the file in so you're at the end of the file and there's nowhere to write the text to.
You can get around this by going back to the beginning of the file with fp.seek(0)
Also surrounding whitespace is being consumed by the regex so you can add it back in.
So your code would be:
with open(r"c:\TestFolder\test_file_with_State.txt","r+") as fp:
    finds = 'MI'
    pattern = re.compile(r'[,\s]+' + re.escape(finds) + r'[\s]+')
    textdata = fp.read()
    line = re.sub(pattern,' MICHIGAN ',textdata)
    fp.seek(0)
    fp.write(line)

