我试图将一个简单的列表制成一个使用tabulate()
,格式的文本文件,fancy_grid
格式是我想要的,它在控制台中打印得很好,但是在写入文本文件时,我得到下面的错误。删除参数tablefmt='fancy_grid'
使它写一个简单的表,但这不是我想要的。我也尝试过使用 docx 格式,但仍然出现相同的错误
这是在 Windows 环境中。
代码
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")
错误
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>