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

前端 未结 4 2008
遥遥无期
遥遥无期 2021-02-08 15:22

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          


        
4条回答
  •  面向向阳花
    2021-02-08 15:50

    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 )
    

提交回复
热议问题