将新字符串添加到现有文本文件时遇到问题

问题描述

我正在处理一些代码来学习如何使用写入和读取方法。到目前为止,我打开了一个名为 output.txt 的文件删除了整行以及该行的最后一个字符。然后我小写 output.txt 中的所有字符。我在将变量 lc 中的内容添加到 output.txt 而不删除 output.txt 中已有的内容时遇到了问题。我尝试了 f.write(lc) ,但出现错误 (io.UnsupportedOperation: not readable)

这是我目前的代码

# open file using "with"
with open("output.txt",'w') as f:
    lines = f.read()
    
    # strip the newline and the last character from what is read in
    newLine = lines.strip()
    lastChar = lines.strip()[len(lines) - 1]

    # convert the text to lower case
    lc = newLine.lower()

    # print the lower-case text and a newline to standard output
    f.write(lc) 

解决方法

你不能使用 w 模式从文件中读取,使用 'r+' 模式,使用 write 方法会根据指针所在的位置将字符串对象写入文件。

# open file using "with"
with open("output.txt",'r+') as f:
    lines = f.read()
    
    # strip the newline and the last character from what is read in
    newLine = lines.strip()
    lastChar = lines.strip()[len(lines) - 1]

    # convert the text to lower case
    lc = newLine.lower()

    # print the lower-case text and a newline to standard output
    f.write(lc)