[英]Reading list of tuples from a file/saving data to a file
我有一個給定學生學期的課程列表。 我想將此類列表保存到名為 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)],[]
Course對象由幾個參數定義:
*作業列表是由名稱、類別和等級定義的作業對象列表
我選擇將類別保留為元組,因為它看起來更容易。
當我在程序啟動時嘗試讀取文件時出現了我的問題。 雖然將分配和類別寫入列表相對簡單,但將其讀回變得更加困難,因為當我將元組列表轉換回例如類別時,似乎有雙引號。
我的問題是:如何更輕松地將 txt 文件中的元組和列表讀入我的程序?
我從閱讀這篇文章開始,但我走到了死胡同,因為這篇文章更多地是關於將元組專門保存到文件中,而我有很多參數需要在啟動程序時轉換為對象。
我想擴大這篇文章,以更多地了解一般的保存文件,以更好地理解我應該如何解決這個問題。
閱讀文件后,我根據保存文件中的參數創建一個新的Course對象,並將其添加到名為“courses”的列表中,稍后可以訪問該列表。
旁注:我什至不確定這種方法是否是最有效的做事方式,所以如果有人對我如何更有效地將課程保存到文件有更好的想法,那么我 100% 對它持開放態度。 我計划將大量課程和作業寫入此文件,因此正確寫入非常重要
感謝您的幫助,這是我在學習路徑的早期開始的一個項目,所以我只想重新訪問它以了解如何將數據保存到文件:p
我將為您提供一個 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)];[]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.