Search code examples
pythonfileoutputprettytable

Writing prettytable in output file in python


I am parsing through a textfile and extracting the information I need into a prettytable. However, I am unable to write the table out as one table it outputs as a single table for each item.

My code for outputting the table:

f = open("out2.txt", "w")
for item in table:
    f.write("%s\n" % item)

f.write("There are %(count)d errors found" %{"count": count})

And my output looks like:

enter image description here

How can i write out the table so that it is one consecutive table?


Solution

  • Does f.write(table.get_string()) work for you? Instead of iterating through the table and writing each item, just write the table itself?

    So something like this, replacing the loop:

    f = open('out2.txt','wb')
    f.write(table.get_string())
    f.write('There are %(count)d errors found' % {'count': count})