我有一個給定學生學期的課程串列。我想將此類串列保存到名為 classes.txt 的 txt 檔案中。這充當一種“保存”檔案。再次打開時,程式將讀取檔案并了解學生正在上什么課。
我使用以下代碼執行此操作:
def write_out():
f_out = open('classes.txt', 'w')
# classes is a list of classes that the student has created
# all the classes are objects which have a few parameters listed below
for course in classes:
f_out.write(str(Course.course_name(course)) ',' str(Course.credits(course)) ',' str() ',' str(Course.assignments(course)) '\n')
寫入檔案的內容如下所示:
Bio,4,[('exam', 100)],[]
calc,4,[('exam', 50)],[]
甲課程目的是通過幾個引數限定:
- 一個名字(即“生物”)
- 學分數
- 課程評分類別的元組串列(類別名稱,然后是權重)
- 作業清單*
*作業串列是由名稱、類別和等級定義的作業物件串列
我選擇將類別保留為元組,因為它看起來更容易。
當我在程式啟動時嘗試讀取檔案時出現了我的問題。雖然將分配和類別寫入串列相對簡單,但將其讀回變得更加困難,因為當我將元組串列轉換回例如類別時,似乎有雙引號。
我的問題是:如何更輕松地將 txt 檔案中的元組和串列讀入我的程式?
我從閱讀這篇文章開始,但我走到了死胡同,因為這篇文章更多地是關于將元組專門保存到檔案中,而我有很多引數需要在啟動程式時轉換為物件。
我想擴大這篇文章,以更多地了解一般的保存檔案,以更好地理解我應該如何解決這個問題。
閱讀檔案后,我根據保存檔案中的引數創建一個新的Course物件,并將其添加到名為“courses”的串列中,稍后可以訪問該串列。
旁注: 我什至不確定這種方法是否是最有效的做事方式,所以如果有人對我如何更有效地將課程保存到檔案有更好的想法,那么我 100% 接受它。我計劃將大量課程和作業寫入此檔案,因此正確寫入非常重要
感謝您的幫助,這是我在學習路徑的早期開始的一個專案,所以我只想重新訪問它以了解如何將資料保存到檔案:p
uj5u.com熱心網友回復:
我將為您提供一個 DIY 解決方案,沒有外部庫,讓您了解作業流程。評論中給出的建議更多的是好的,但下劃線的原則應該是“相似的”。
此處不考慮性能、安全性,將其視為您學習路徑的編碼更新(或者我希望如此)。
要求:
- 在寫入檔案時使用唯一的分隔符,當您稍后閱讀它時會更容易。我選擇
;但可以自由更改它(,與串列沖突,& co) - 在撰寫字串物件時,“雙雙”參考它們,以便在檔案中它們將被雙引號包圍(需要
eval查看下一步),因此字串應具有以下形式'"Bio"' - 用于
eval將字串“復活”為物件 - 在課程類中添加寫/讀方法。特別地,讀取器是一個類方法,因為它回傳一個類實體
class Course:
SEP = ';' # should be a unique character(s)
def __init__(self, name, credits_, grading_cats, assignments):
self.name, self.credits, self.grading_cats, self.assignments = self.data = name, credits_, grading_cats, assignments
def __str__(self): # not needed but useful to understand the difference with "write_file_formatter", see 2.
return f'{self.SEP}'.join( str(i) for i in self.data)
def write_file_formatter(self):
return f'{self.SEP}'.join( f'"{i}"' if isinstance(i, str) else str(i) for i in self.data)
@classmethod
def read_file_formatter(cls, course_string):
return cls(*map(eval, course_string.split(cls.SEP)))
# the courses
c1 = Course('Bio', 4, [('exam', 100)], [])
c2 = Course('cal', 4, [('exam', 50)], [])
print(c1.write_file_formatter())
# "Bio";4;[('exam', 100)];[]
print(c2.write_file_formatter())
# "cal";4;[('exam', 50)];[]
# simulate text file
courses_from_file = c1.write_file_formatter() '\n' c2.write_file_formatter()
# "Bio";4;[('exam', 100)];[]
# "cal";4;[('exam', 50)];[]
# simulate read from file
for course in courses_from_file.split('\n'):
c = Course.read_file_formatter(course)
print(type(c), c)
# <class '__main__.Course'> Bio;4;[('exam', 100)];[]
# <class '__main__.Course'> cal;4;[('exam', 50)];[]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336731.html
下一篇:與串列的所有向量成對比較
