【问题标题】:Python tabulate not writing to text file correctlyPython制表未正确写入文本文件
【发布时间】:2021-01-11 05:22:22
【问题描述】:

我试图将一个简单的列表制成一个使用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>

【问题讨论】:

标签: python tabulate


【解决方案1】:

请加:.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")

信用:UnicodeEncodeError: 'charmap' codec can't encode characters

【讨论】:

    【解决方案2】:

    我在linux下运行它。它有效。

    我认为问题不在于tabulate,而在于写入文件

    您可以尝试使用utf-8文件格式保存文件:

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

    【讨论】:

    • 在 Windows 上它在编码后工作。我已编辑问题以表明这一点。
    • @JohnnKaita 我为这种情况添加了其他解决方案。如果你有选择,总是好的)
    猜你喜欢
    • 2020-10-06
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    相关资源
    最近更新 更多