UnicodeEncodeError Python?

时间:2016-12-15 09:11:51

标签: python python-3.x

尝试写入文件时出现以下错误:

    public static void main(String[] args) {
        List <User> list = new ArrayList<>();
        list.add(new User("A1", "B1", "Name1"));
        list.add(new User("A2", "B2", "Name2"));
        list.add(new User("A3", "B3", "Name3"));
        list.add(new User("A4", "B4", "Name4"));
        list.add(new User("A5", "B5", "Name5"));

        System.out.println(list.get(Collections.binarySearch(list, new User("A4", "B4", "Name4"))));
    }


    static class User implements Comparable <User>{
        String territory;
        String company;
        String name;

        public User(String territory, String company, String name) {
            this.territory = territory;
            this.company = company;
            this.name = name;
        }

        @Override
        public int compareTo(User o) {
            return (territory+company).compareTo(o.territory+o.company);
        }

        @Override
        public String toString(){
            return territory + "," + company + "," + name;
        }
    }

我尝试在文件中写下此文UnicodeEncodeError('ascii', u'B\u1ea7u cua (B\u1ea7u cua 2017 )', 1, 2, 'ordinal not in range(128)'))

Bầu cua

我还尝试使用f = codecs.open("13.txt", "a", "utf-8") f.write("{}\n".format(title))

它给了我一个新的错误:

当我使用title.encode()时,我收到以下错误:`

.encode(text)

2 个答案:

答案 0 :(得分:2)

正如this answer所述“将Unicode文本写入文本文件?”,您有很多解决方案。

基本上,您有两个问题:

必须在str.format()对象

上使用unicode方法
u'{}\n'.format('Bầu cua')

您写入的文件也必须使用正确的编码打开:

f = open('13.txt', 'a', encoding='utf-8')

因此,这适用于Python 3:

data = 'Bầu cua'
f = open('13.txt', 'a', encoding='utf-8')
line = u'{}\n'.format(data)
f.write(line)
f.close()

答案 1 :(得分:0)

尝试在文件开头使用这两行。它适用于Python2.7

#!/usr/bin/env python
# -*- coding: utf-8 -*-

data = u'Bầu cua'
f = open('test.txt', 'a')
line = u'{}\n'.format(data)
f.write(line.encode('utf8'))
f.close()