Search code examples
pythonfileunsupportedoperation

UnsupportedOperation: not writable python


 with open(r'G:\Programs\abc.txt') as f:
    for line in f:
          if line.startswith('logan'):
                 f.write('Johann Sebastian Bach')
                 print("Renewed line = ", line)

error message:

    runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')
Traceback (most recent call last):

  File "<ipython-input-2-393638b0e5ce>", line 1, in <module>
    runfile('G:/Python Programs/p17.py', wdir='G:/Python Programs')

  File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "G:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "G:/Python Programs/p17.py", line 11, in <module>
    khand.write('Johann Sebastian Bach')

UnsupportedOperation: not writable

I have listed this code in python3.6 still I am getting an error message. I have required file in directory. Any suggestions?


Solution

  • Opening the file without a mode defaults to opening it in readonly mode. If you want to write to it while reading, you've to specify the mode as r+.

    with open(r'G:\Programs\abc.txt', mode='r+') as khand:
        ...
    

    w+ will also open the file in r/w mode, however, it wipes the contents clean.

    You also use the a+ mode which will append to the end of the file, while still letting you read from it.