微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在处理一些代码来学习如何使用写入和读取方法。到目前为止,我打开了一个名为 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) 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。