Pickle 与 Python 中输出到文件的比较
我有一个程序可以输出一些我想要存储以供以后使用的列表。例如,假设它输出学生姓名列表和期中成绩的另一个列表。我可以通过以下两种方式存储此输出:
标准文件输出方式:
newFile = open('trialWrite1.py','w')
newFile.write(str(firstNames))
newFile.write(str(midterm1Scores))
newFile.close()
pickle 方式:
newFile = open('trialWrite2.txt','w')
cPickle.dump(firstNames, newFile)
cPickle.dump(midterm1Scores, newFile)
newFile.close()
哪种技术更好或首选?使用其中一种比另一种有优势吗?
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为
csv
模块可能很适合这里,因为 CSV 是一种标准格式,可以由 Python(以及许多其他语言)读写,而且也是人类可读的。用法可以很简单,但是,每行写一个学生(包括他们的姓名和分数)可能更有意义。可以这样做:
I think the
csv
module might be a good fit here, since CSV is a standard format that can be both read and written by Python (and many other languages), and it's also human-readable. Usage could be as simple asHowever, it'd probably make more sense to write one student per row, including their name and score. That can be done like this:
pickle
更通用——它允许您将许多不同类型的对象转储到文件中以供以后使用。缺点是临时存储不太可读,并且不是标准格式。另一方面,将字符串写入文件是与其他活动或代码更好的接口。但这是以必须再次将文本解析回 Python 对象为代价的。
对于这个简单的(列表?)数据来说,两者都很好;我会使用 write(firstNames) 只是因为不需要使用 pickle。一般来说,如何将你的数据持久化到文件系统取决于数据!
例如,
pickle
会愉快地 pickle 函数,而这是您无法通过简单地编写字符串表示来完成的。pickle
is more generic -- it allows you to dump many different kinds of objects to a file for later use. The downside is that the interim storage is not very human-readable, and not in a standard format.Writing strings to a file, on the other hand, is a much better interface to other activities or code. But it comes at the cost of having to parse the text back into your Python object again.
Both are fine for this simple (list?) data; I would use
write( firstNames )
simply because there's no need to use pickle. In general, how to persist your data to the filesystem depends on the data!For instance,
pickle
will happily pickle functions, which you can't do by simply writing the string representations.对于完全不同的方法,请考虑 Python 附带 SQLite。您可以将数据存储在 SQL 数据库中,而无需添加任何第三方依赖项。
For a completely different approach, consider that Python ships with SQLite. You could store your data in a SQL database without adding any third-party dependencies.