Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: write a list with non-ASCII characters to a text file

I'm using python 3.4 and I'm trying to write a list of names to a text file. The list is as follows:

my_list = ['Dejan Živković','Gregg Berhalter','James Stevens','Mike Windischmann',
               'Gunnar Heiðar Þorvaldsson']

I use the following code to export the list:

file = open("/Users/.../Desktop/Name_Python.txt", "w")
file.writelines( "%s\n" % item for item in my_list )
file.close()

But it does not work. Python seems not to like non-ASCII characters and gives me the following errors:

"UnicodeEncodeError: 'ascii' codec can't encode character '\u017d' in position 6: ordinal not in range(128)"

Do you know if there is a way to solve this problem ? Maybe it's possible to write files in UTF-8 / unicode ?

like image 603
Jb_Eyd Avatar asked Oct 21 '15 09:10

Jb_Eyd


People also ask

How do I read non-ASCII characters in Python?

Approach 1: This approach is related to the inbuilt library unidecode. This library helps Transliterating non-ASCII characters in Python. It provides an unidecode() method that takes Unicode data and tries to represent it in ASCII.

Can you write a list to a file in Python?

We can write multiple lines at once using the writelines() method. For example, we can pass a list of strings to add to the file. Use this method when you want to write a list into a file. As you can see in the output, the file writelines() method doesn't add any line separators after each list item.

How do I use non-ASCII characters?

This is easily done on a Windows platform: type the decimal ascii code (on the numeric keypad only) while holding down the ALT key, and the corresponding character is entered. For example, Alt-132 gives you a lowercase "a" with an umlaut.


Video Answer


1 Answers

The issue is that the file is getting openned with ascii encoding (which might be what is returned by locale.getpreferredencoding() for your environment). You can try openning with the correct encoding (maybe utf-8) . Also, you should use with statement so that it handles closing the file for you.

For Python 2.x , you can use codecs.open() function instead of open() -

with codecs.open("/Users/.../Desktop/Name_Python.txt", "w",encoding='utf-8') as file:
    file.writelines( "%s\n" % item for item in my_list )

For Python 3.x , you can use the built-in function open() , which supports encoding argument. Example -

with open("/Users/.../Desktop/Name_Python.txt", "w",encoding='utf-8') as file:
    file.writelines( "%s\n" % item for item in my_list )
like image 52
Anand S Kumar Avatar answered Sep 18 '22 22:09

Anand S Kumar