【问题标题】:AttributeError: 'str' object has no attribute 'write' when adding a string to a txt.fileAttributeError:将字符串添加到 txt.file 时,“str”对象没有属性“write”
【发布时间】:2023-03-13 00:50:01
【问题描述】:

我正在尝试学习如何在 Python 3.7 上打开 txt.files。 我有一个包含以下内容的文件(Days.txt):

星期一 周二 周三 周四 星期五 周六 周日

在 Jupyter 上,我使用了以下代码:

f = open('Days.txt','r').read()
f

这给了我以下结果:

'星期一\n星期二\n星期三\n星期四\n星期五\n星期六\n星期日'

到目前为止,一切都很好。

然后,我尝试在 Days.txt 文件中添加一句话:

f.write('this is a test\n')

这就是我收到以下错误消息的地方:

AttributeError Traceback(最近一次调用最后一次) 在 ----> 1 f.write('这是一个测试\n')

AttributeError: 'str' 对象没有属性 'write'

为什么它不起作用?

下面的代码导致另一个错误消息:

file = open('Days.txt','r')
s = file.read()
file.write('this is a test\n')
file.close()

---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-138-0cc4cd12a8b3> in <module>
      1 file = open('Days.txt','r')
      2 s = file.read()
----> 3 file.write('this is a test\n')
      4 file.close()

UnsupportedOperation: not writable

【问题讨论】:

  • 说明f其实是一个字符串。在尝试写入之前,请检查 type(f)。此外,在读取文件时,最好在 with 子句中执行它,例如 with open(days.txt) as f: ..... 最后在将内容附加到文件末尾时,您需要指定 'a ' 参数,如 f.write('text', 'a')

标签: python-3.x string


【解决方案1】:

因为f是字符串,不是文件指针,所以最好把文件指针放在自己的变量中:

f = open('Days.txt', 'r')

s = f.read() # <-- check the content if you need it
print(s)

f.write('this is a test\n')

f.close() # <-- remember to close the file

最好还是自动关闭文件:

with open('Days.txt', 'r') as f:
    s = f.read()
    print(s)
    
    f.write('this is a test\n')

【讨论】:

    【解决方案2】:

    以写入模式打开文件以允许向其中添加新内容。 为此,只需

    f = open("Days.txt", "a")
    f.write("This is a text\n")
    f.close()
    

    记得在打开文件处理程序后关闭它。 不过,我建议您使用“with”构造,它会在读/写操作后自动关闭文件处理程序

    with open("Days.txt", "a") as f:
        f.write("This is a text\n")
    

    【讨论】:

      猜你喜欢
      • 2017-07-06
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多