【问题标题】:TreeView.insert throws UnicodeDecodeErrorTreeView.insert 抛出 UnicodeDecodeError
【发布时间】:2018-11-19 14:28:01
【问题描述】:

我正在尝试使用来自 os.listdir(path) 的数据填充 TreeView。

在我读取带有非 utf 字符的目录名称之前一切正常。在我的情况下,0xf6 不是 utf8。

当我在 Windows 上运行时,来自 os.listdir() 的字符集是 Windows-1252 或 ANSI。

如何解决这个问题以在 TreeView 中正确显示?

这是我的一些代码:

def fill_tree(treeview, node):
    if treeview.set(node, "type") != 'directory':
        return

    path = treeview.set(node, "fullpath")
    # Delete the possibly 'dummy' node present.
    treeview.delete(*treeview.get_children(node))

    parent = treeview.parent(node)
    for p in os.listdir(path):
        ptype = None
        p = os.path.join(path, p)

        if os.path.isdir(p):
            ptype = 'directory'

        fname = os.path.split(p)[1].decode('cp1252').encode('utf8')

        if ptype == 'directory':
            oid = treeview.insert(node, 'end', text=fname, values=[p, ptype])
            treeview.insert(oid, 0, text='dummy')

问候 戈兰

【问题讨论】:

  • 在 PyPi 上有很多“treeview”的匹配项。您具体使用哪个库?并且:有问题的字典键是什么类型,strunicode
  • 我正在使用 Tkinter。不明白您关于“冒犯字典键”的问题?
  • 抱歉,我没有仔细阅读。我的意思是“目录名”。但我很确定os.listdir() 返回str,而不是unicode。您可以使用name.decode('cp1252') 解码目录名称,它会为您提供一个Unicode 字符串。然后检查 TreeView.insert 是否接受这个。
  • 我试过 name.decode('cp1252').encode('utf8') ,它工作正常。但是当我继续循环遍历目录树时遇到了麻烦 - os.path.isdir(p) 无法使用 utf 编码按预期工作? Catch-22 情况?
  • 听起来您需要保留单独的变量:os.* 的 CP-1252 版本和 TreeView 的 UTF-8 版本。或者你切换到 Python 3,一切都应该使用 Unicode 字符串。

标签: windows python-2.7 utf-8 treeview


【解决方案1】:

UnicodeDecodeError 是由于在函数需要 Unicode 字符串时传递字节字符串。 Python 2 尝试将字节字符串隐式解码为 Unicode。改为显式使用 Unicode 字符串。 os.listdir(unicode_path) 将返回 Unicode 字符串,例如 os.listdir(u'.')

【讨论】:

    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 2023-03-18
    • 2016-04-25
    • 2014-10-24
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多