Python“AttributeError:'_io.TextIOWrapper”对象没有属性“append'”错误

2024-05-23 19:36:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这是代码,它不起作用

for i in range(100):
    with open("New Text Document.txt", "a") as f:
        f.append("Q.) \n")

它显示“AttributeError:”\u io.TextIOWrapper“对象没有属性'append'”错误

我用这个印了同样的

for i in range(1, 100):
    f = open("IT TextBook Ques.txt", 'r')
    f2 = f.read()
    f1 = f"""{f2}
    Q.) \n"""
    f.close()
    f3 = open("IT TextBook Ques.txt", 'w')
    f3.write(f1)

但是为什么第一个不起作用呢

我正在使用Python 3.8.7


Tags: 代码intxtnewforwithrangeit
2条回答

因为它确实没有任何名为append的方法

您可以通过dir验证这一点:

>>> f = open('/tmp/test.yml', 'a')
>>> dir(f) ['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines']

在本例中,对于_io.TextIOWrapper,“append”是打开文件的模式

要调用的方法是write

这就是为什么第一个例子不起作用,而第二个却起作用

文件没有append()方法。如果要附加文件,只需在“a”模式下打开文件并使用f.write() 您也可以使用第二个代码,但这是一个漫长的过程。 因此,您应该使用:

for i in range(100):
    f=open("Your Document.txt", 'a')
    f.write("Q.) \n")
    f.close()

相关问题 更多 >