I’m making a working phone book with linked list.
I am trying to save data in a txt file.
The write command only takes str into it.
How can I convert temp.data.name to str.I mean linked list object to str.
I got the same error when I typed str(temp.data.name) at the beginning too.
temp = linked_list.head
f = open("phonebook.txt", "w")
while temp:
namestr = " ".join(temp.data.name)
f.write(namestr)
numberstr = " ".join(temp.data.number)
f.write(numberstr)
temp = temp.next
f.close()
>Solution :
Here is simple example to store phonebook in linked list and save it to file:
from __future__ import annotations
import dataclasses
@dataclasses.dataclass
class Record(object):
name: str
number: str
@dataclasses.dataclass
class Node(object):
data: Record
next: Node = None
head = Node(Record('Alice', '123'), Node(Record('Bob', '456')))
with open('phonebook.txt', 'w', encoding='utf-8') as f:
temp = head
while temp:
f.write(f'{temp.data.name} - {temp.data.number}\n')
temp = temp.next