我的代码遇到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'
答案 0 :(得分:1)
您的各个Reservation对象没有写属性。您要调用文件的write方法,并使用对象的数据填充字符串。
with open("reservation.txt", "w") as file_:
for reservation in reservationList:
file_.write(reservation.passengerName + .... + "\n")
旁注,由于您使用的是上下文管理器(open()为_),因此无需执行file.close()
。经理会帮你做。
此外,file
是内置函数,因此您不想覆盖它。您需要在变量名称后附加一个下划线,以区分变量as described in PEP8
答案 1 :(得分:0)
reservation只是一个遍历列表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()
下面是打开文件并读取文件的示例:
file1 = open("myfile.txt","r")
print(file1.read())
print(file1.readline())
答案 2 :(得分:0)
执行此操作,并确保列表中的最后一个字符串具有\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")