Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

write() argument must be str, not LinkedList

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading