我想知道如何在关闭python文件时保存添加到列表中的内容。例如,在下面我写的这个“我的联系人”程序中,如果添加有关“简·多伊”的信息,该怎么做,以便下次打开同一文件时,简·多伊仍然存在。
def main():
myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
def __init__(self, peoples):
self.peoples = peoples
self.main_menu()
def main_menu(self):
print('Main Menu')
print('1. Display Contact Names')
print('2. Search For Contacts')
print('3. Edit Contact')
print('4. New Contact')
print('5. Remove Contact')
print('6. Exit')
self.selection = input('Enter a # form the menu: ')
if (self.selection == "1"):
self.display_names()
if (self.selection == "2"):
self.search()
if (self.selection == "3"):
self.edit()
if (self.selection == "4"):
self.new()
if (self.selection == "5"):
self.delete()
if (self.selection == "6"):
self.end()
def display_names(self):
for people in self.peoples:
print("Name: " + people["name"])
self.main_menu()
def search(self):
searchname = input('What is the name of your contact: ')
for index in range(len(self.peoples)):
if (self.peoples[index]["name"] == searchname):
print("Name: " + self.peoples[index]["name"])
print("Address: " + self.peoples[index]["address"])
print("Phone: " + self.peoples[index]["phone"])
self.main_menu()
def edit(self):
searchname = input('What is the name of the contact that you want to edit: ')
for index in range(len(self.peoples)):
if (self.peoples[index]["name"] == searchname):
self.peoples.pop(index)
name = input('What is your name: ')
address = input('What is your address: ')
phone = input('What is your phone number: ')
self.peoples.append({"name": name, "phone": phone, "address": address})
self.main_menu()
def new(self):
name = input('What is your name: ')
address = input('What is your address: ')
phone = input('What is your phone number: ')
self.peoples.append({"name": name, "phone": phone, "address": address})
self.main_menu()
def delete(self):
searchname = input('What is the name of the contact that you want to delete: ')
for index in reversed(range(len(self.peoples))):
if (self.peoples[index]["name"] == searchname):
self.peoples.pop(index)
print(searchname, 'has been removed')
self.main_menu()
def end(self):
print('Thank you for using the contact book, have a nice day')
print('Copyright Carson147 2019©, All Rights Reserved')
main()
答案 0 :(得分:3)
使用标准库的Data Persistence部分中的模块,或将其另存为json或csv file。
答案 1 :(得分:1)
有无数种序列化选项,但是经过时间考验的最爱是JSON。 JavaScript对象表示法如下:
[
"this",
"is",
"a",
"list",
"of",
"strings",
"with",
"a",
{
"dictionary": "of",
"values": 4,
"an": "example"
},
"can strings be single-quoted?",
false,
"can objects nest?",
{
"I": {
"Think": {
"They": "can"
}
}
}
]
JSON被广泛使用,并且Python stdlib在json
包中提供了一种将对象与JSON相互转换的方法。
>>> import json
>>> data = ['a', 'list', 'full', 'of', 'entries']
>>> json.dumps(data) # dumps will dump to string
["a", "list", "full", "of", "entries"]
然后您可以在程序关闭之前将Book数据保存到json,并在程序启动后从json读取。
# at the top
import json
from pathlib import Path
# at the bottom of your program:
if __name__ == '__main__':
persistence = Path('book.json')
if persistence.exists():
with persistence.open() as f:
data = json.load(f)
else:
data = [{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}]
book = Book(data)
with persistence.open('w') as f:
json.dump(f, indent=4)
答案 2 :(得分:0)
您只需在函数中将列表转换为数组即可。
np.save('path/to/save', np.array(your_list))
加载:
arr=np.load(''path/to/save.npy').tolist()
我希望这会有所帮助
答案 3 :(得分:0)
没有任何外部模块(例如numpy
或pickle
),您将无法做到这一点。使用pickle
,您可以执行以下操作:(我假设您要保存myBook
变量)
import pickle
pickle.dump(myBook, open("foo.bar", "wb")) #where foo is name of file and bar is extension
#also wb is saving type, you can find documentation online
要加载:
pickle.load(myBook, open("foo.bar", "rb"))
编辑:
我的第一句话是错的。有一种无需导入模块即可保存的方法。方法如下:
myBook.save(foo.bar) #foo is file name and bar is extention
要加载:
myBook=open(foo.bar)
答案 4 :(得分:0)
从许多其他答案可以看出,有很多方法可以做到这一点,但我认为举个例子会有所帮助。
通过这样更改文件的顶部,可以使用搁置模块。
如果您有好奇心,还可以在代码中解决许多其他问题,如果需要更多反馈,可以尝试https://codereview.stackexchange.com/。
import shelve
def main():
default = [
{'name': 'John Doe', 'phone': '123-456-7890',
'address': '1000 Constitution Ave'}
]
with Book('foo', default=default) as myBook:
myBook.main_menu()
class Book:
def __init__(self, filename, default=None):
if default is None:
default = []
self._db = shelve.open(filename)
self.people = self._db.setdefault('people', default)
def __enter__(self):
return self
def __exit__(self):
self._db['people'] = self.people
self._db.close()