慕的地6264312
2021-05-31 06:58:21
我是python語言的新手。我想將一行保存到文件并加載文件的特定行。問題是我應該讀取(加載)該文件的一行作為另一個(等級)類的對象,或者將一行作為另一個類(等級)的對象保存到文件中我做到了,我想看看我做對了嗎!class Grade(): def __init__(self,student_id=0,course_id=0,score=0): self._student_id = student_id self._course_id = course_id self._score = score @property def get(self): return str(self._student_id)+" "+str(self._course_id)+" "+str(float(self._score)) @property def student_id(self): return str(self._student_id) @property def course_id(self): return str(self._course_id) @property def score(self): return str(self._score) @student_id.setter def student_id(self,student_id: int): self._sutdent_id = student_id @course_id.setter def course_id(self,course_id: int): self._course_id = course_id @score.setter def score(self,score: float): self._score = scoreclass CourseUtil(): def __init__(self): self._address = '' def set_file(self,address): self._address = address def load(self,line_number): fp = open(self._address) for i, line in enumerate(fp): if i+1 == line_number: stri= line.split(" ") stdid = int(stri[0]) corid = int(stri[1]) score = float(stri[2]) #here I want to save the #object that passed as argument to a file is it right? grade = Grade(stdid,corid,score) fp.close() return(grade) return print("None")在保存功能中,我檢查數據是否唯一,并且避免在文件末尾使用最后\ n
1 回答

千巷貓影
TA貢獻1829條經驗 獲得超7個贊
您使用的保存類條目行的模型效率低下。相反,您可以以更好的方式存儲數據。我假設每個學生ID是唯一且可哈希的(字符串或整數)。因此,您可以簡單地擁有一本包含每個學生所有信息的字典:
student_information = {
{student_id}: {
course_id: {course_id},
score: {score}
},
... # more students
}
現在,如果您想獲取學生的信息,您可以簡單student_information[student_id]地獲取所需的數據。例如,你可以這樣做:
grade = Grade(
student_id,
student_information[student_id]["course_id"],
student_information[student_id]["score"]
)
您可以輕松地將此字典設置為類的實例變量CourseUtil。
現在,@juanpa.arrivillaga 提到您應該使用它pickle來存儲該信息(如果您想稍后返回)。使用Pickle,您可以將數據像字典一樣存儲到文件中并加載。也json可以幫助您做同樣的事情。
添加回答
舉報
0/150
提交
取消