2

I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.

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()
4

5 Answers 5

3

Use a module from the Data Persistence section of the standard library, or save it as json, or as a csv file.

Sign up to request clarification or add additional context in comments.

Comments

1

You just convert your list to array inside in function .

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

to load :

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

I hope it will be helpful

3 Comments

And you think the OP is using numpy, why?
To develop myself, can you explain why my solution is bad ?
The OP is very obviously a beginner. Numpy is not really meant for beginners. Throwing numpy into the mix as a way to persist things is going to be confusing for a beginner.
1

There are innumerable kinds of serialization options, but a time-tested favorite is JSON. JavaScript Object Notation looks like:

[
    "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 is widely used, and the Python stdlib has a method of converting objects to and from JSON in the json package.

>>> import json
>>> data = ['a', 'list', 'full', 'of', 'entries']
>>> json.dumps(data)  # dumps will dump to string
["a", "list", "full", "of", "entries"]

You can then save your Book data to json before the program shuts down, and read from json after it starts up.

# 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)

Comments

0

There is no way you can do that without any external modules, such as numpy or pickle. Using pickle, you can do this: (I am assuming you want to save the myBook variable)

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

To load:

pickle.load(myBook, open("foo.bar", "rb"))

EDIT:

I was wrong in my first statement. There is a way to save without importing a module. Here is how:

myBook.save(foo.bar) #foo is file name and bar is extention

To load:

myBook=open(foo.bar)

2 Comments

where does the .save method come from? Your edit looks wrong. There definitely is a way to do this without importing a module, but that way is basically "write your own serialization method" which is without a doubt much harder.
I am not 100% sure if it works for lists, but I used it for an image, and it worked perfectly fine
0

As evinced by the many other answers, there are many ways to do this, but I thought it was helpful to have a example.

By changing the top of your file as so, you can use the shelve module.

There are a variety of other things you can fix in your code if you are curious, you could try https://codereview.stackexchange.com/ if you want more feedback.

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.