AttributeError: тип объекта '' не имеет атрибута 'write' - PullRequest
0 голосов
/ 08 октября 2019

Мой код сталкивается с ошибкой AttributeError, и я не знаю, как это исправить

это мой класс:

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'

Ответы [ 3 ]

1 голос
/ 08 октября 2019

Ваши отдельные объекты Reservation не имеют атрибутов записи. Вы хотите вызвать метод записи файла и использовать данные объекта для заполнения строки.

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

Примечание: поскольку вы используете менеджер контекста (с open () в качестве _), вам не нужно делать file.close(). Менеджер сделает это за вас.

Кроме того, file является встроенным, поэтому вы не хотите перезаписывать это. Вы захотите добавить одно подчеркивание к имени переменной, чтобы дифференцировать его , как описано в PEP8

0 голосов
/ 08 октября 2019

Сделайте это следующим образом и убедитесь, что ваша последняя строка в вашем списке имеет \n, чтобы каждый раз, когда другой пользователь вводил информацию, которую он записывает в новой строке:

with open("file_name.txt", 'a') as f: # "a" is used to append data to a file that is it
# does not delete previously written data instead appends to it also f is the variable 
# which stores the file and could be anything
    for reservation in reservationList:
        f.write(reservation)
    print("done")
0 голосов
/ 08 октября 2019

резервирование - это просто итератор для обхода списка bookingList, в нем не определены функции записи. Существует три способа чтения данных из текстового файла.

read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.

File_object.read([n])

readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.

File_object.readline([n])

readlines() : Reads all the lines and return them as each line a string element in a list.

  File_object.readlines()

Вот пример для открытия и чтения файла:

file1 = open("myfile.txt","r") 
print(file1.read()) 
print(file1.readline()) 
...