Search code examples
pythoniopsycopg2stringio

Error expected type StringIO, got str instead


I'm trying to bulk insert data into my postgres database using the copy_from function from psycopg2. To use this function, I'm trying to put a list of tuples into a file-like object using io.StringIO (python 3.x).

    def __insert_cpe_dic__(self, cpe_dic):
        sio = StringIO
        sio.write('\n'.join(cpe for cpe in cpe_dic))
        sio.seek(0)
        self.cur.copy_from(sio, "cpe_dictionary")

I get the error: 'expected type StringIO, got str instead ...' when writing to the 'sio' variable. I couldn't find any answer to my problem and hope someone has an idea.


Solution

  • You assigned a class not an instance of a class when you did sio = StringIO. You need to add parens to instantiate an instance of the class: sio = StringIO(). Also, you don't need the explicit generator, just doing sio.write('\n'.join(cpe_dic)) will produce the same result.