Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

Python tabulate not writing to text file correctly

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...