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:Pythonlibencodingscp1252.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>
question from:
https://stackoverflow.com/questions/65661704/python-tabulate-not-writing-to-text-file-correctly 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…