Search code examples
pythonpython-3.xattributeerror

AttributeError: type object ' ' has no attribute 'write'


My code runs into an AttributeError and I don't know how to fix it

this is my class:

class Reservation:

    def __init__(self, passengerName, departureCity, destinationCity, dateOfTravel, timeOfTravel, numberOfTickets):
        self.passengerName = passengerName
        self.departureCity = departureCity
        self.destinationCity = destinationCity
        self.dateOfTravel = dateOfTravel
        self.timeOfTravel = timeOfTravel
        self.numberOfTickets = numberOfTickets

reservationList = list()
with open("reservation.txt", "w") as file:

    for reservation in reservationList:
        reservation.write(reservation.passengerName + "," + reservation.departureCity + "," + reservation.destinationCity +
                            "," + reservation.dateOfTravel + "," + reservation.timeOfTravel + "," +
                            str(reservation.numberOfTickets) + "\n")

    file.close()
File "C:/Users//Desktop/pld/ticket_reservation5.py", line 183, in <module>
    main()
  File "C:/Users//Desktop/pld/ticket_reservation5.py", line 176, in main
    reservation.write(reservation.passengerName + "," + reservation.departureCity + "," + reservation.destinationCity +
AttributeError: type object 'Reservation' has no attribute 'write'

Solution

  • Your individual Reservation objects don't have write attributes. You want to call the file's write method and use the object's data to populate the string.

    with open("reservation.txt", "w") as file_:
        for reservation in reservationList:
            file_.write(reservation.passengerName + .... + "\n")
    

    Side note, since you're using a context manager (with open() as _), you don't have to do file.close(). The manager will do it for you.

    Also, file is a builtin so you don't want to overwrite that. You'll want to append a single underscore to the variable name to differentiate it as described in PEP8