简体   繁体   English

从文件中读取元组列表/将数据保存到文件

[英]Reading list of tuples from a file/saving data to a file

I have a list of classes in a given student's semester.我有一个给定学生学期的课程列表。 I want to save this list of classes to a txt file named classes.txt.我想将此类列表保存到名为 classes.txt 的 txt 文件中。 This acts as a sort of "save" file.这充当一种“保存”文件。 When opened again, the program will read the file and know what classes the student is taking.再次打开时,程序将读取文件并了解学生正在上什么课。

I do so with the following code:我使用以下代码执行此操作:

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')

The contents of the written file look like this:写入文件的内容如下所示:

Bio,4,[('exam', 100)],[]
calc,4,[('exam', 50)],[]

A Course object is defined by a few parameters: Course对象由几个参数定义:

  1. A name (ie 'Bio')一个名字(即“生物”)
  2. Number of credits学分数
  3. a list of tuples for the course's grading categories(name of category, then weight)课程评分类别的元组列表(类别名称,然后是权重)
  4. List of assignments*作业清单*

*List of assignments is a list of Assignment objects which are defined by a name, category it is, and a grade *作业列表是由名称、类别和等级定义的作业对象列表

I have chosen to leave a category as a tuple as it just seems easier.我选择将类别保留为元组,因为它看起来更容易。


My problem arises when I try to read the file when the program is started.当我在程序启动时尝试读取文件时出现了我的问题。 While its relatively simple to write the assignments and categories into a list it becomes more difficult to read it back in as there appear to be double quotes when I convert the list of tuples back over for example with the categories.虽然将分配和类别写入列表相对简单,但将其读回变得更加困难,因为当我将元组列表转换回例如类别时,似乎有双引号。

My question is: How can I read tuples and lists from a txt file more easily into my program?我的问题是:如何更轻松地将 txt 文件中的元组和列表读入我的程序?

I started by reading this post but I hit a dead end as this post is more about saving tuples specifically to a file while I have lots of parameters that need to be converted over to objects when starting the program.我从阅读这篇文章开始,但我走到了死胡同,因为这篇文章更多地是关于将元组专门保存到文件中,而我有很多参数需要在启动程序时转换为对象。

I wanted to broaden this post to be more about save files in general to better understand how I should approach this problem.我想扩大这篇文章,以更多地了解一般的保存文件,以更好地理解我应该如何解决这个问题。

After reading the file I create a new Course object given the parameters in the save file and add it to a list named 'courses' which can be accessed later.阅读文件后,我根据保存文件中的参数创建一个新的Course对象,并将其添加到名为“courses”的列表中,稍后可以访问该列表。

Side note: I am not even sure that this method is even the most efficient way of doing things so if anyone has a better idea on how I can more effectively save courses to a file then I am 100% open to it.旁注:我什至不确定这种方法是否是最有效的做事方式,所以如果有人对我如何更有效地将课程保存到文件有更好的想法,那么我 100% 对它持开放态度。 I plan on having a lot of classes and assignments being written to this file so it is important that this is written correctly我计划将大量课程和作业写入此文件,因此正确写入非常重要

Thanks for any help and this was a project I started early on in my learning path so I just wanted to revisit it to see how to save data to files :p感谢您的帮助,这是我在学习路径的早期开始的一个项目,所以我只想重新访问它以了解如何将数据保存到文件:p

I will provide you a DIY solution, no external libraries, to give an idea of the workflow.我将为您提供一个 DIY 解决方案,没有外部库,让您了解工作流程。 The advises given in the comments are more the good but the underline principles should be "similar".评论中给出的建议更多的是好的,但下划线的原则应该是“相似的”。

Performance, safety are not considered here, consider it just as a coding refresh for your learning path (or I hope so).此处考虑性能、安全性,将其视为您学习路径的编码更新(或者我希望如此)。

Requirements :要求

  1. use a unique separator symbol when writing to a file, it is easier when you will have read it in a second moment.在写入文件时使用唯一的分隔符,当您稍后阅读它时会更容易。 I choose ;我选择; but be free to change it (the , gives conflicts with lists, & co)但可以自由更改它( ,与列表发生冲突,& co)
  2. when writing string objects "double double" quote them so that in the file they will be surrounded by doubles quotes (needed for eval see next step), so a string should be of the form '"Bio"'在编写字符串对象时,“double double”引用它们,以便在文件中它们将被双引号包围(需要eval请参阅下一步),因此字符串应采用'"Bio"'形式
  3. use eval to "resurrect" the string to an object使用eval将字符串“复活”为对象
  4. add write/read methods in the course class.在课程类中添加写/读方法。 In particular, the reader is a classmethod since it returns an class instance特别地,读取器是一个类方法,因为它返回一个类实例
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM