python write umlauts into file

5.3k views Asked by At

i have the following output, which i want to write into a file:

l  = ["Bücher", "Hefte, "Mappen"]

i do it like:

f = codecs.open("testfile.txt", "a", stdout_encoding)
f.write(l)
f.close()

in my Textfile i want to see: ["Bücher", "Hefte, "Mappen"] instead of B\xc3\xbccher

Is there any way to do so without looping over the list and decode each item ? Like to give the write() function any parameter?

Many thanks

1

There are 1 answers

4
Laurent LAPORTE On

First, make sure you use unicode strings: add the "u" prefix to strings:

l  = [u"Bücher", u"Hefte", u"Mappen"]

Then you can write or append to a file:

I recommend you to use the io module which is Python 2/3 compatible.

with io.open("testfile.txt", mode="a", encoding="UTF8") as fd:
    for line in l:
        fd.write(line + "\n")

To read your text file in one piece:

with io.open("testfile.txt", mode="r", encoding="UTF8") as fd:
    content = fd.read()

The result content is an Unicode string.

If you decode this string using UTF8 encoding, you'll get bytes string like this:

b"B\xc3\xbccher"

Edit using writelines.

The method writelines() writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value.

# add new lines
lines = [line + "\n" for line in l]

with io.open("testfile.txt", mode="a", encoding="UTF8") as fd:
    fd.writelines(lines)