首页 > 解决方案 > Python 2.7 import unicode_literals from __future__ 在使用 umauts 读取文件时给出 UnicodeDecodeError

问题描述

我有一个 Python 脚本,它在输入文件“myfile.in”中读取和写入带有德语变音符号 (äöü) 的文件。我使用了 Python 2.7 版。这是我的脚本的简化版本:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
if __name__=='__main__':       
    with open("myfile.in", "r") as f:
        lines = f.readlines()  
    txt = ""        
    for line in lines: 
        txt = txt + line
    with open("myfile.out", "w") as f:
        f.write(txt) 

这工作正常。

现在我从客户那里得到了使用 Future 语句定义的要求,我在我的 Python 脚本中添加了以下行:

from __future__ import unicode_literals

现在我收到以下错误消息:

Traceback (most recent call last):
  File "myscript.py", line 9, in <module>
    txt = txt + line
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 23: ordinal not in range(128)

我该如何解决这个问题。谢谢你的提示托马斯

标签: python-2.7filecodecdiacritics

解决方案


推荐阅读