Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - write non-ascii characters to file

I am on Linux and a want to write string (in utf-8) to txt file. This is my code:

# -*- coding: UTF-8-*-

import os
import sys


def __init__(self, dirname, speaker, file, exportFile):

      text_file = open(exportFile, "a")

      text_file.write(speaker.encode("utf-8"))
      text_file.write(file.encode("utf-8"))

      text_file.close()      

When I am on Windows, it works. But on Linux, I get this error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position in position 36: ordinal not in range(128)

How can I solve this problem? Thank you.

like image 499
user3375111 Avatar asked Mar 03 '14 13:03

user3375111


1 Answers

You could try to use the "codecs" module:

import codecs

with codecs.open('filename', 'w', encoding='utf-8') as out:  
    out.write(u'some text')
like image 145
dugres Avatar answered Sep 17 '22 18:09

dugres