4

Am trying to tabulate a simple list into a text file formatted using tabulate(), fancy_grid format is what i want and it prints alright in the console, however upon writing to text file, I get the error below. Removing the argument tablefmt='fancy_grid' makes it write a simple table, but it isn't what I want. I have also tried using docx format but still get the same error

This is on a Windows environment.

Code

from tabulate import tabulate

l = [['{:<118}.'.format("Hassan"), 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]
table = tabulate(l, headers=['Name', 'Age', 'University'], tablefmt='fancy_grid', showindex="always")

with open("C:\\Users\\John\\Desktop\\kaita.txt", "w") as outf:
    outf.write(table)
os.startfile("C:\\Users\\John\\Desktop\\kaita.txt", "print")

Error

Traceback (most recent call last):
  File "E:/Developement/Desktop Applications/GuiWithWx/Learn/Teach/runpython.py", line 160, in <module>
    outf.write(table)
  File "C:\Python\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-150: character maps to <undefined>
Johnn Kaita
  • 432
  • 1
  • 3
  • 13

2 Answers2

1

Please add: .encode("utf-8").

from tabulate import tabulate

l = [['{:<118}.'.format("Hassan"), 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]
table = tabulate(l, headers=['Name', 'Age', 'University'], tablefmt='fancy_grid', showindex="always")

with open("C:\\Users\\John\\Desktop\\kaita.txt", "w") as outf:
    outf.write(table.encode("utf-8"))
os.startfile("C:\\Users\\John\\Desktop\\kaita.txt", "print")

credit: UnicodeEncodeError: 'charmap' codec can't encode characters

antoine
  • 662
  • 4
  • 10
1

I ran it under linux. it works.

enter image description here

I think the problem is not in tabulate but in writing to the file

You can try save file with utf-8 file format:

import io
from tabulate import tabulate

l = [['{:<118}.'.format("Hassan"), 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]
table = tabulate(l, headers=['Name', 'Age', 'University'], tablefmt='fancy_grid', showindex="always")

with io.open("C:\\Users\\John\\Desktop\\kaita.txt", "w", encoding="utf-8") as outf:
    outf.write(table)

os.startfile("C:\\Users\\John\\Desktop\\kaita.txt", "print")    
Daniil Loban
  • 4,165
  • 1
  • 14
  • 20