How to convert a list inside of a class to a string in Python in order to be able to write it a txt file?

Question:

So I have a class which contains an empty list, static and instance methods. When I add new instances which contain strings to this class, they get appended to this empty list and everything is working correctly. I’m trying to write a function that will get this list and write it in a txt file but instead of the actual content, I’m getting something like this when I try the map() function:

"0x000001E6B9C718D0><Products.Product"

And if I type a simple .join and convert the list to a string, it’s showing me this error:

"The Python "TypeError: can only join an iterable"

which tells me the list is not being properly converted to a string.

I’ve looked online extensively for the past 2 hours but so far nothing. None of the solutions have fixed my problem. Probably because this list is inside a class and instances are getting appended to it but I don’t know.

EDIT: Forgot the code here it is:

class Product:
#This class is for adding products.

products = []
def __init__(self, name, serial_number, price):
    self.name = name
    self.serial_number = serial_number
    self.price = price

#Instance method to show the information about an instance.
def show(self):
    print("Product's Name:", self.name, "|", "Serial Number:", self.serial_number, "|", "Price:", self.price)

#Class method to add a product to the product's list.
@staticmethod
def add_product(product):
    Product.products.append(product)

#Class method to show the info of all products
@staticmethod
def show_products():
   for product in Product.products:
       product.show()

#Class method to write th items in a txt file:
@staticmethod
def write_list():
    file = open("Products.txt", "a")
    file.write(''.join(str(Product.products))) 
        

     
        

            
            
Asked By: SaintDev

||

Answers:

It seems you’re trying to concatenate a list of instances to a string. When you use join to concatenate the list, it throws an error because it expects an iterable of strings.

You can simply convert each instance to a string and then write to your file.
Something like this;

with open("output.txt", "w") as f:
    f.write('n'.join(str(p) for p in Product.products_list))

Edit Modified function in given code example

@staticmethod
def write_list():
    with open("Products.txt", "w") as file:
        for product in Product.products:
            file.write(product.name + ',' + product.serial_number + ',' + str(product.price) + 'n')

The issue is that function is currently writing the Product.products list directly to the file without properly formatting the contents. As a result, you’re seeing the memory address of each instance instead of the actual data.

Answered By: Raghav Kukreti

You likely want to serialize the class instead with pickle. Converting a class to a string yourself is a bad idea, you should let the standard library do it for you instead. pickle serializes into binary, you likely want to encode that. binary in base64 to make it look like regular text. Like this:

import base64
import pickle


class MyClass:
    def __init__(self, lst=[]):
        self.lst = lst

    def add(self, val):
        self.lst.append(val)


myObj = MyClass([1])
myObj.add(2)

s = base64.b64encode(pickle.dumps(myObj)).decode('utf-8')
print(s)  # => gASVLQAAAAAAAACMCF9fbWFpbl9flIwHTXlDbGFzc5STlCmBlH2UjANsc3SUXZQoSwFLAmVzYi4=

You can then read it the string back from the file and decode it:

import base64
import pickle


class MyClass:
    def __init__(self, lst=[]):
        self.lst = lst

    def add(self, val):
        self.lst.append(val)
        

s = "gASVLQAAAAAAAACMCF9fbWFpbl9flIwHTXlDbGFzc5STlCmBlH2UjANsc3SUXZQoSwFLAmVzYi4="
obj = pickle.loads(base64.b64decode(s))
print(obj.lst)  # => [1, 2]
Answered By: Michael M.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.