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>
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