UnsupportedOperation:不可写的python

时间:2017-07-04 15:06:29

标签: 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 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

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

1 个答案:

答案 0 :(得分:6)

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

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

w+也将以r / w模式打开文件,然而,它会清除内容。

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