简体   繁体   English

文件编辑和保存

[英]File editing and saving

My (python) application loads a file into memory and lets the user do incremental edits/saves on the data. 我的(python)应用程序将文件加载到内存中,并允许用户对数据进行增量编辑/保存。 The data is mostly key/value pairs, so I was thinking of using JSON to represent the information. 数据主要是键/值对,因此我考虑使用JSON来表示信息。 The application will be a user's only means to access the data, so the exact format of the stored data is driven solely by the application design. 应用程序将是用户访问数据的唯一方法,因此存储数据的确切格式仅由应用程序设计驱动。 The file size will never grow too large, so running out of memory is not a constraint. 文件大小永远不会变得太大,因此内存不足也不是限制因素。 Every time a user decides to "save", is there a better way of persisting the information to disk than completely wiping the old file and writing the new data? 每次用户决定“保存”时,是否有更好的方法将信息保存到磁盘而不是完全擦除旧文件并写入新数据?

The object will have to be converted to JSON and written to disk each time you want to save. 每次要保存时,都必须将对象转换为JSON并写入磁盘。 You might want to investigate whether shelve can meet your needs. 您可能想要调查shelve是否可以满足您的需求。 You can persist a dictionary to disk using strings as keys and update specific keys as needed... 您可以使用字符串作为键将字典保存到磁盘,并根据需要更新特定的键...

import shelve
db = shelve.open('data.db')
print db['keyname']
db['keyname'] = 'some new user data'
db.sync()
db.close()

The main advantage of shelve is ease of use. shelve的主要优点是易于使用。 Disadvantages include slow access with big files, lack of cross-system compatibility, and inability to trust files from third-party sources. 缺点包括使用大文件访问速度慢,缺乏跨系统兼容性以及无法信任来自第三方来源的文件。 So if users are expected to email files to each other or otherwise share content over a network, shelve would not be a secure choice. 因此,如果希望用户通过网络向彼此发送电子邮件或以其他方式共享内容,则shelve将不是一个安全的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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