问题
I have a small problem here. Im trying to load a txt file that i have saved eariler while doing a session in my console application. When i load the file. the dictionary appears like this:
1111 ['peter']
7777 ['frida']
1337 ['john', 'johnny']
2121 ['peter', 'foppa']
the numbers are the keys that are linked to the persons/aliases. When i load it and try to add new aliases my functions cant find the names..
When i add new persons or create aliases to existing persons with an empty dictionary it looks like this instead:
1337 killer
1337 murderer
6677 sebastian
My add function looks like this:
def add(self,name,number):
p = phonebook(name)
if number in self.dictList:
print("nummret finns redan")
else:
self.dictList[number] = [p]
print("Ny person sparad")
My alias function looks like this:
def alias(self,name,newName,number = None):
self.checkIfNameExist(name)
if self.checkIfNameExist(name) == None:
print("telebok> finns ingen med det namnet")
else:
self.isNameMoreThenOne(name)
if self.isNameMoreThenOne(name) == 1:
print(self.isNameMoreThenOne(name))
#getnumber
number = self.returnNumberFromName(name)
name = newName
p = phonebook(name)
#save object with append
self.dictList[number].append(p)
#save object with append
print("telebok> nytt alias skapat")
elif self.isNameMoreThenOne(name) > 1:
if number:
name = newName
p = phonebook(name)
self.dictList[number].append(p)
print("telebok> nytt alias har skapats")
else:
print("Det finns flera med samma namn, skriv in numret")
My save to a textfile function looks like this:
def save(self,filename):
f = open(filename,"w")
for number in self.dictList:
printNumber = (str(number + ";"))
f.write(printNumber)
keys = self.dictList[number]
for name in keys:
printName = str(name.name + ";")
print(printName)
f.write(printName)
f.write("\n")
f.close()
And my load function from a textfile looks like this:
def load(self,filename):
dList = {}
f = open(filename,"r")
for readLine in f:
readLine = readLine.split(";")
number = readLine[0]
#print(number)
nameLength = len(readLine[1:])
#print(nameLength)
name = readLine[1:nameLength]
p = phonebook(name)
self.dictList[number] = dict()
#print(name)
self.dictList[number] = [p]
print(self.dictList)
f.close()
Everything works when i run the program from the start and do everything step by step adding a new person. creating an alias for a name, creating an alias for an existing alias etc. Something is going completly wrong when i save or load the textfile. My guess is on the load function. Does any of you have any suggestion what i could do instead to read from a textfile and use the program as i do before i save/load from a textfile?
来源:https://stackoverflow.com/questions/52802680/loading-data-from-textfile-to-a-dictionary-in-python