我正在嘗試在 python 中做簡單的學生管理專案。我正在嘗試將物件寫入檔案,但它不起作用。當我嘗試寫它時,它只寫一個學生,它不會寫到下一行。
class Student:
def __init__(self,fname,lname,age,major):
self.fname=fname
self.lname=lname
self.age=age
self.major=major
def accept(self,fname,lname,age,major):
ls=[str(fname),str(lname),str(age),str(major)]
with open('student.txt', 'w') as f:
f.writelines(ls)
obj=Student('','','','')
obj.accept('Samet','Saricicek','21','student')
obj.accept('Emre','Saricicek','24','student')
obj.accept('Ezgi','Saricicek','25','student')
uj5u.com熱心網友回復:
這里
with open('student.txt', 'w') as f:
f.writelines(ls)
您以寫入模式打開檔案w,這樣做您將洗掉檔案的現有內容,如果您不想這樣做,請使用a(附加)模式
with open('student.txt', 'a') as f:
f.writelines(ls)
有關可用模式的進一步討論,請參閱open內置函式檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446359.html
上一篇:根據舊的和更正的串列查找和替換檔案中的一組代碼/單詞
下一篇:視窗默認檔案夾以不同的語言顯示
