0
#open file and rewrite (comma) to ,
with open('outputFile') as fo:
    fo.write(line.replace("(comma)"," , "))

I'm trying to replace the text (comma) with a literal , within a file. When I run the above code, I get the following error: io.UnsupportedOperation: not writable

Any insight as to how to rewrite text within a file would be greatly appreciated.

I've used the below code, and it still won't replace (comma) with ,

#open file and rewrite (comma) to , with open('outputFile.txt', "a+") as fo: fo.write(fo.replace('(comma)',',')) fo.close()

pHorseSpec
  • 1,246
  • 5
  • 19
  • 48

4 Answers4

3

You need to open the file in read/write mode using the 'r+' argument.

Once you read the file contents, clear it using seek(0) and truncate(), and then write the new text.

with open('outputFile', 'r+') as f:
    text = f.read()
    f.seek(0)
    f.truncate()
    f.write(text.replace('(comma)', ' , '))
Nitesh Patel
  • 631
  • 3
  • 10
1

You get the "not writeable" error because you need to open the file for writing, done by passing the mode argument to open:

with open('outputFile', "w") as fo:
    fo.write(line.replace("(comma)"," , "))

Depending on the behaviour you want, you may want to use a mode other than "w", which truncates the file if it exists. Check out the Python documentation on open for more details.

If you still get an error then there may be a permissions problem writing to the file.


To actually perform a replacement on each line in the file have a look at this question or this question.

DanielGibbs
  • 9,910
  • 11
  • 76
  • 121
1

fileinput will allow you to read/write to the same file pretty easily ...

with fileinput.input("out.txt") as fo:
     for line in file:
         print line.replace("(comma)"," , ")
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Try opening the file in write mode:

with open('outputFile', 'w+') as fo:
    fo.write(line.replace("(comma)"," , "))
Jules
  • 14,200
  • 13
  • 56
  • 101