我正在编写一个Python程序来维护一个联系人列表,每个联系人都有3个字段:
联系人需要保存在YAML结构化文件中,该程序应该提供添加新联系人的功能。
我的代码是:
class contacts:
def add_contact(self,file,contact):
if not os.path.exists(file):
#Creating for the first time
temp = []
temp.append(contact)
with open(file, "w") as file_desc:
yaml.dump(temp, file_desc, default_flow_style=False)
file_desc.close()
else:
#Second onwards
with open(file, "r") as file_desc:
loaded = yaml.safe_load(file_desc)
loaded.append(contact)
with open(file, "w") as file_desc2:
yaml.dump(loaded, file_desc2, default_flow_style=False)
file_desc2.close()
file_desc.close()
if __name__ == "__main__":
data1 = {'name' :'Abcd', 'phone': 1234, 'email': '[email protected]'}
data2 = {'name': 'efgh', 'phone': 5678, 'email': '[email protected]'}
contact = contacts()
contact.add_contact("contacts.yaml", data1)
contact.add_contact("contacts.yaml",data2)
我认为这是一个效率低下的实现。如果我们有100万个联系人,并且我们想要添加一个新联系人,这将首先读取所有联系人,将其中一个附加到列表并再次写入所有1百万+ 1个联系人。有没有办法只需添加新的联系人而无需再次写入整个文件。我想阅读很重要,因为我不想存储重复的联系人,这需要比较。任何其他有效的方法也将受到赞赏。
在长期运行的程序/过程P中,确实不需要重新读取数据。有几点需要注意:
atexit
执行此操作如果您使用真实数据库,并且对于简单的记录表,所有具有相同字段的上述内容都可以为您完成,这可能是更好的选择。然而,一旦事情变得更复杂:每个记录的不同字段,复杂和可能的递归数据,那么许多(SQL)数据库成为另一个问题,而不是帮助解决您尝试解决的问题。
ruamel.yaml.base
(免责声明:我是该套餐的作者)为您提供开箱即用的项目2),其他两项也很容易实现。唯一棘手的问题是YAMLBase
通常期望在根级别为新文件设置映射/字典,因此当文件尚不存在时需要进行一些强制操作。
你做pip install ruamel.yaml.base
之后:
import os
import ruamel.yaml
from ruamel.yaml.base import YAMLBase
yaml_path = 'contacts.yaml'
class Contacts(YAMLBase):
def __init__(self, path=yaml_path, verbose=0):
self._create_ok = True # so the file is auto created if it doesn't exists
super().__init__(path=path, verbose=verbose)
if not os.path.exists(yaml_path):
# this is necessary to force block style sequence at the top
self._data = ruamel.yaml.comments.CommentedSeq()
self._changed = True
def add_record(self, contact):
self.data.append(contact)
self._changed = True # this signals that writing is necessary
def dump_file(self):
"""dump the contents of the file on disc"""
print('dumping: "{}"'.format(self._path))
with open(yaml_path) as fp:
print(fp.read(), end='')
data1 = {'name' :'Abcd', 'phone': 1234, 'email': '[email protected]'}
data2 = {'name': 'efgh', 'phone': 5678, 'email': '[email protected]'}
contacts = Contacts()
contacts.add_record(data1)
contacts.save() # optional
contacts.dump_file()
# this is just for checking
contacts.add_record(data2)
contacts.save()
contacts.dump_file()
这使:
dumping: "contacts.yaml"
- name: Abcd
phone: 1234
email: [email protected]
dumping: "contacts.yaml"
- name: Abcd
phone: 1234
email: [email protected]
- name: efgh
phone: 5678
email: [email protected]
如果将verbose
参数设置为1
,您将获得有关stdout的一些信息,了解包中的内容。
如果你有很多记录,那么你可能想要将self.data
中的Contacts
更改为self.fast_data
,然后使用更快的基于C的加载器加载YAML,代价是无法保留(手动添加)注释等。输入YAML。 (在任何一种情况下都使用“safe_load”)。