-6
 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 中列出了这段代码,但我仍然收到一条错误消息。我在目录中有所需的文件。有什么建议么?

4

1 回答 1

6

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

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

w+也将以 r/w 模式打开文件,但是,它会将内容擦除干净。

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

于 2017-07-04T15:09:37.900 回答