繁体   English   中英

将列表数据保存在python中

[英]Saving list data in python

我想知道如何在关闭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()

使用标准库“ 数据持久性”部分中的模块,或将其另存为jsoncsv文件

您只需将列表转换为function内部的数组。

np.save('path/to/save', np.array(your_list))

装载 :

arr=np.load(''path/to/save.npy').tolist()

希望对您有所帮助

序列化选项有无数种,但是经过时间考验的最爱是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)

没有任何外部模块(例如numpypickle ,您将无法做到这一点。 使用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)

正如许多其他答案所表明的那样,有很多方法可以做到这一点,但是我认为举一个例子会有所帮助。

这样改变文件的顶部,就可以使用搁置模块。

如果您感到好奇,还可以在代码中解决许多其他问题,如果需要更多反馈,可以尝试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()

暂无
暂无

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

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