不支持操作:不可写python

不支持操作:不可写python,python,file,unsupportedoperation,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) runfile('G:/Python程序/p17.py',wdir='G:/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)
runfile('G:/Python程序/p17.py',wdir='G:/Python程序')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
运行文件('G:/Python程序/p17.py',wdir='G:/Python程序')
文件“G:\Anaconda3\lib\site packages\spyder\utils\site\sitecustomize.py”,第880行,在runfile中
execfile(文件名、命名空间)
文件“G:\Anaconda3\lib\site packages\spyder\utils\site\sitecustomize.py”,第102行,在execfile中
exec(编译(f.read(),文件名,'exec'),命名空间)
文件“G:/Python Programs/p17.py”,第11行,在
写(‘约翰·塞巴斯蒂安·巴赫’)
不支持操作:不可写

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

不使用模式打开文件默认为以只读模式打开。如果要在读取时写入,必须将模式指定为
r+

    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
w+
也将以r/w模式打开文件,但会将内容清除干净


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

您以只读方式打开文件……此外,向当前正在读取的文件写入可能会产生令人惊讶的结果。但即使在添加“w”时,我也会收到错误消息。我检查了我的文件权限。没有模棱两可之处@JamesKent@SubhamChatterjee请不要在帖子中使用“Bakchodi”,它的味道很差。过滤你的问题使其可读。好的@coldspeedh我该怎么做@输入@HueMan的ColdSpeedHanks
with open(r'G:\Programs\abc.txt', mode='r+') as khand:
    ...