UnsupportedOperation:不可写的python

-6 python file unsupportedoperation

 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)
Run Code Online (Sandbox Code Playgroud)

错误信息:

    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
Run Code Online (Sandbox Code Playgroud)

我已经在python3.6中列出了这段代码,但仍然收到错误消息.我在目录中需要文件.有什么建议?

cs9*_*s95 6

在没有模式的情况下打开文件默认以只读模式打开它.如果要在阅读时写入,则必须将模式指定为r+.

with open(r'G:\Programs\abc.txt', mode='r+') as khand:
    ...
Run Code Online (Sandbox Code Playgroud)

w+也将以r/w模式打开文件,但是,它会清除内容.

您还可以使用a+将附加到文件末尾的模式,同时仍然允许您从中读取.