1

I am trying to write to a textfile in python where the the output in the file. I have a Class called phonebook which has a list containing objects of the phonebook class.

My constructor looks like this:

def __init__(self,name,number):
        self.name = name
        self.number = number

When i add a new object to the list looks like this:

def add(self):
    name = input()
    number = input()
    p = Phonebook(name,number)
    list.append(p)

When I'm writing my list to the textfile the function looks like this:

def save():
    f = open("textfile.txt","w")
    for x in list:
       f.write(x.number+";"+x.name+";")
    f.close()

And its writes out:

12345;david;12345;dave;12345;davey;09876;cathryn;09876;cathy; and so on..

should look like this:

12345;david,dave,davey
09876;cathryn,cathy,
78887;peter,pete,petr,petemon

My question is then.. How do I implement this save function so it will only write out one unique number and all its names connected to that number? Feels like its impossible to do with only a list containing names and numbers.. Maybe im wrong..

teslagosu
  • 65
  • 5
  • 3
    I would advise you use a Python dictionary (which acts as a hashmap) instead of a list. You can use the phone number as the key, and then store a list of Phonebook entries as the value for each key in the dict associated with each number. Then to write them out just iterate over each key/value pair in your dict saving them to the file – Karl Oct 10 '18 at 02:28
  • Thank you for your answer. I guess I could do that. but I must at the same time be able to add new aliases to a already existing person and change an existing persons name to something else and delete every person that is connected to one number. Is this possible with a dictionary? – teslagosu Oct 10 '18 at 02:38
  • 1
    Yes all of those things sound like standard programming operations that you can do on the objects stored in the dictionary. The dictionary is a data structure used to store references to objects which you can reference and modify. A list also works in the same way, but different data structures are more helpful in certain cases. (Dict is better then a list in this case to associate all the items by the same key) – Karl Oct 10 '18 at 02:43
  • 1
    Also you probably want to look up about using the `del` keyword for how to remove the items from a dict. It will make it _very_ easy to remove all Phonebooks associated with the same key. – Karl Oct 10 '18 at 02:46
  • 1
    you create variables that you would later use as dictionary keys. but also keep the numbers in list to track them. so if that value has already been used tell the program to return the dictionary value name – Herc01 Oct 10 '18 at 02:53
  • Thank you again @Karl, I may have got stuck on one part where my proffessor told us that the easiest way to solve this is by not using a dictionary. I have been struggleing for days on just how to write it out to a file in that exact way. But the dictionary solves alot of problems :) – teslagosu Oct 10 '18 at 02:55

2 Answers2

2

Dictionaries in Python give you fast access to items based on their key. So a good solution to your problem would be to index the Phonebook objects using the Phonebook.number as the key to store a list of Phonebooks as the values. Then at the end just handle the printing based on however you want each line to appear.

This example should work in your case:

phone_dict = dict() # Used to store Phonebook objects intead of list

def add(self):
    name = input()
    number = input()
    p = Phonebook(name,number)

    if p.number in phone_dict:
       phone_dict[p.number].append(p)  # Append p to list of Phonebooks for same number
    else:
       phone_dict[p.number] = [p] # Create list for new phone number key

def save():
    f = open("textfile.txt","w")

    # Loop through all keys in dict
    for number in phone_dict:
       f.write(x.number + ";")  # Write out number
       phone_books = phone_dict[number]

       # Loop through all phone_books associated with number
       for i, pb in enumerate(phone_books):
           f.write(pb.name)
           # Only append comma if not last value
           if i < len(phone_books) - 1:
               f.write(",")

       f.write("\n") # Go to next line for next number
    f.close()
Karl
  • 1,664
  • 2
  • 12
  • 19
  • Thank you @Karl for your answer. I think this is what im look for! – teslagosu Oct 10 '18 at 02:47
  • How would the syntax look if i wanted to load it from a txt file into the program @Karl ? – teslagosu Oct 12 '18 at 11:05
  • u still out there? – teslagosu Oct 16 '18 at 21:35
  • @teslagosu [This thread](https://stackoverflow.com/questions/3277503/in-python-how-do-i-read-a-file-line-by-line-into-a-list) can probably help you out. Also since your question now is about a different topic (reading the data to the dict), I would suggest maybe asking a separate question related to that if you are having issues, since this thread's question about writing the data out has been solved. – Karl Oct 16 '18 at 21:39
  • here is my other question :) [link](https://stackoverflow.com/questions/52802680/loading-data-from-textfile-to-a-dictionary-in-python) – teslagosu Oct 16 '18 at 21:45
0

so how would the load function look? I have tried doing one, and it loads everything into the dictionary but the program doesnt function with my other functions like it did before i saved it and reload it to the program again..

def load(self,filename):
self.dictList = {}
f = open(filename,"r")
for readLine in f:
    readLine = readLine.split(";")
    number = readLine[0]            

    nameLength = len(readLine[1:])

    name = readLine[1:nameLength]
    p = phonebook(name)


    self.dictList[number] = [p]
    print(self.dictList)
f.close()
teslagosu
  • 65
  • 5