AttributeError:类型对象“”没有属性“write”

2024-05-23 19:44:35 发布

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

我的代码遇到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()
^{pr2}$
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'

Tags: selfticketusersfileattributeerrordesktopreservationpld
3条回答

您的单个保留对象没有写入属性。您需要调用文件的write方法并使用对象的数据填充字符串。在

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

另请注意,由于您使用的是上下文管理器(open()作为u),所以您不必执行file.close()。经理会为你做的。在

另外,file是一个内置项,所以您不想覆盖它。您需要在变量名后附加一个下划线来区分它as described in PEP8

reservation只是遍历list reservationList的迭代器,它没有定义任何写函数。 从文本文件中读取数据有三种方法。在

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()

以下是打开并读取文件的示例:

^{pr2}$

这样做,并确保列表中的最后一个字符串有一个\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")

相关问题 更多 >