6

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.

5
  • 1
    Are you sure you don't want to decode('utf-8') to convert your utf8 string to a bytestring? Commented Mar 3, 2014 at 14:01
  • do you have a sample or a link to your source? Commented Mar 3, 2014 at 14:14
  • Have you tried opening the file in "au" mode? Commented Mar 3, 2014 at 14:17
  • Yes, I tried "au" mode. I got the same error. Commented Mar 3, 2014 at 14:28
  • Can you try to use mode "ab" (binary mode), which is described in documentation to avoid text mode? Commented Mar 3, 2014 at 14:45

1 Answer 1

9

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')
Sign up to request clarification or add additional context in comments.

1 Comment

With Python 2 it could help to use "u strings"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.