0

When I run this code, I get results like:

(3205, Decimal('1.000'))(28802, Decimal('7.000'))(3106, Decimal('1.000'))(3173, Decimal('5.000')). 

I don't want to see the "decimal" word included in the output, how do I avoid this?

cur.execute('SELECT tk_product_ord, SUM(tk_qty_ord) as qty_required '
        'FROM table1 WHERE tk_date = 15047 AND tk_prod_group = 11 '
        'GROUP BY tk_product_ord;')

answer = cur.fetchall()

file = open("test_data_output.txt")
with open("test_data_output.txt", "w") as line:
    for item in answer:
        line.write("%s\n" % str(item))
    file.close()
ph140
  • 478
  • 3
  • 10
haribo
  • 3
  • 1
  • see https://stackoverflow.com/questions/7483363/python-mysqldb-returns-datetime-date-and-decimal – balderman Oct 01 '21 at 12:44
  • FYI, the `file = open("test_data_output.txt")` and `file.close()` are redundant. The `with open("test_data_output.txt", "w") as line` is a context manager, it will automatically close `line`. – Adrian Klaver Oct 01 '21 at 15:19

2 Answers2

0

The issue is you're using str(item), which will include the Decimal type name in the repr call to those objects.

By converting the decimal to a float you will remove this:

Instead of line.write("%s\n" % str(item)) you can do something like line.write(f"{item[0]}, {float(item[1])}")

Luke Storry
  • 6,032
  • 1
  • 9
  • 22
0

In for item in answer:, item is a tuple. In Python, if the call str on a tuple, or another collection like a list or dict, the items in the collections are shown as their repr rather than their str.

To get the output that you want, call str on each element of item and call str.join on the result:

with open("test_data_output.txt", "w") as line:
    for item in answer:
        output = ' '.join([str(elem) for elem in item])
        line.write("%s\n" % output)

The expression [str(elem) for elem in item] is a list comprehension, a way of generating a list from an existing sequence object like a list or tuple.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153