-1

I don't understand why I can't use append when I am appending to a file.

This is my code:

# opening capital.txt and append to it
files = open('capitals.txt', 'a') 
userInput = input('Type the name of the city you want to add on capitals: ')

# If I change this to files.write it works
files.append(f'{userInput}') 
files.close()

I just need an explanation of why .write works but not .append

When I use .append I get this error:

> AttributeError: '_io.TextIOWrapper' object has no attribute 'append'
auraham
  • 1,679
  • 2
  • 20
  • 27
  • 1
    Why do you think `'_io.TextIOWrapper' object has no attribute 'append'`? What made you think it would have an `append` method anyway? – wjandrea Aug 13 '20 at 02:07
  • BTW welcome to SO! Check out the [tour] and [ask]. – wjandrea Aug 13 '20 at 02:07
  • 1
    Does this answer your question? [How do you append to a file in Python?](https://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) – Gino Mempin Aug 13 '20 at 02:09
  • 1
    [TextIOWrapper has no append](https://docs.python.org/3/library/io.html#io.TextIOWrapper). – Gino Mempin Aug 13 '20 at 02:13
  • 2
    "I just need an explanation why .write works but not .append" because, as the error message clearly states, '_io.TextIOWrapper' object has no attribute 'append'. What exactly are you asking? Are you asking *why* that is the case? Because the answer to that is: because the designers of the API wrote it that way. – juanpa.arrivillaga Aug 13 '20 at 02:19
  • 2
    it doesnt work because append is not a class method, it doesnt exist... write does...and when you open a file using 'append' write method, it means when you write, you are appending – Derek Eden Aug 13 '20 at 02:20
  • @DerekEden Thank you that explain it clearly and concise. Exactly the answer I was looking for! – Alfredo Giron Aug 13 '20 at 06:06

2 Answers2

0

files is an instance of _io.TextIOWrapper

In [14]: isinstance(files, _io.TextIOWrapper)                                                                                                                  
Out[14]: True

Also, files does not have the append function:

In [15]: hasattr(_io.TextIOWrapper, "write")                                                                                                                  
Out[15]: True

In [16]: hasattr(_io.TextIOWrapper, "append")                                                                                                                 
Out[16]: False

I think this is a more pythonic version of your code:

with open("capitals.txt", "a") as log:
    msg = input("Type the name of the city: ")
    log.write("{}\n".format(msg))
auraham
  • 1,679
  • 2
  • 20
  • 27
-2

Switch out the append command and put write. (Keep 'a'). This is because there is an append command; however, that is used for adding an element to a list, whereas the write command will edit a file.

bays2023
  • 5
  • 4