开发者社区> 问答> 正文

为什么toml.load(f)在Windows下(但在Linux上不是)对该文件失败?

我有一个要使用此脚本处理的TOML文件。

过去在Linux下可以正常工作。在Windows下(Win32`上的Python 3.6.5 | Anaconda,Inc. |(默认,Mar 29 2018,13:23:52)[MSC v.1900 32位(Intel)])我得到以下错误:

Need to process 1 file(s)
Processing file test01.toml (1 of 1)
Traceback (most recent call last):
  File "py/process.py", line 27, in <module>
    add_text_fragment(input_dir + "/" + file)
  File "<string>", line 10, in add_text_fragment
  File "C:\Users\1\Anaconda3\lib\site-packages\toml\decoder.py", line 134, in lo
ad
    return loads(f.read(), _dict, decoder)
  File "C:\Users\1\Anaconda3\lib\encodings\cp1251.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 985: char
acter maps to <undefined>

我假设错误发生在这里:

f = open(toml_file_name, "r")
pt = toml.load(f)
f.close()

根据NotePad ++,有问题的文件具有UTF-8编码。

我该如何解决?

赏金条款

我将向一位向我展示如何确保脚本process.py正确处理输入文件的人提供这笔赏金,即,执行将超出addTextFragment.py中以If If pt开头的注释

def add_text_fragment(toml_file_name):
    f = open(toml_file_name, "r")
    pt = toml.load(f)
    f.close()

    # If at this point pt contains dthe data of the input file,
    # then you have attained the goal.
    if (pt["type"] == "TA"):

变量pt包含输入文件中的数据。

您的解决方案必须在Windows 10,Python 3.7.6(默认值,2020年1月8日,20:23:39)下运行[MSC v.1916 64位(AMD64)] :: Anaconda,Inc. on win32

注意:process.py对特定目录中的所有文件执行addTextFragment.py。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 18:00:45 872 0
1 条回答
写回答
取消 提交回答
  • 只需替换此行:

    f = open(toml_file_name, "r")
    

    与:

    f = open(toml_file_name, "r", encoding="utf-8")
    

    如您在错误消息中所看到的,Python尝试使用文件的默认系统编码来读取文件-如果文件包含任何非ASCII字符并且在Linux中工作,则意味着它具有不同的编码-并且默认所有非Windows世界的编码都是utf-8。

    回答来源:stackoverflow

    2020-03-24 18:00:54
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
深入解析数据存储技术原理及发展演进—Linux开源存储技术 立即下载
TAKING WINDOWS 10 KERNEL 立即下载
ECS运维指南之Windows系统诊断 立即下载