1

I'm trying to collect output of a postgres query in ods-file using following code. I have created a function read_table that reads the postgres table successfully.

def read_table()
     import psycopg2 as ps
     import sys

      con =None
      try:
      con=ps.connect("host, dbname, user,pwd....")
      cur=con.cursor()
      cur.execute("Select * from table_name")
      rows=cur.fetchall()
      for(row in rows):
            print(row)
      cur.close()
      except (Exception, ps.DatabaseError) as error:
      print(error)
      finally:
          if con is not None:
             con.close()

  from collections import OrderedDict
  from pyexcel_ods import save_data
  data=OrderedDict()
  raw_data=read_table()
  raw_data.update({'DATA':raw_data})
  save_data("/home/myfile.ods", raw_data)

The table is printed on python shell but it is not written to .ods-file. It gives following error:

raw_data.update({'DATA':raw_data})
AttributeError: 'NoneType' object has no attribute

How do I save & extract the table in ods-file? All the packages & modules are installed, but still I get this error.

I'm a newbie in python, so please guide me. I'm using Postgres database on Ubuntu, using Idle3.

5th
  • 2,097
  • 3
  • 22
  • 41
  • Welcome to Stackoverflow. Please edit your question to clarify your problem description. This should help you to find more answers. For guidance please check the [how to ask](https://stackoverflow.com/help/how-to-ask) page and [how to create a minimal example](https://stackoverflow.com/help/mcve). And take the tour! – 5th Sep 07 '18 at 12:24

1 Answers1

0

Your method raw_data does not return anything. Instead of printing the rows, you want to return them or yield them, like so: return row or yield row instead of print(row)

However, it is possible to do what you need in couple of lines of code with pandas library: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html

halucka
  • 26
  • 3