Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print symbols like ● to files in Python

Tags:

python

symbols

I'm trying to write the symbol to a text file in python. I think it has something to do with the encoding (utf-8). Here is the code:

# -*- coding: utf-8 -*-
outFile = open('./myFile.txt', 'wb')
outFile.write("●")
outFile.close()

Instead of the black "●" I get "â—". How can I fix this?

like image 499
Jesper Lundin Avatar asked Apr 19 '15 13:04

Jesper Lundin


2 Answers

Open the file using the io package for this to work with both python2 and python3 with encoding set to utf8 for this to work. When printing, When writing, write as a unicode string.

import io
outFile = io.open('./myFile.txt', 'w', encoding='utf8')
outFile.write(u'●')
outFile.close()

Tested on Python 2.7.8 and Python 3.4.2

like image 89
Alok Mysore Avatar answered Nov 05 '22 11:11

Alok Mysore


If you are using Python 2, use codecs.open instead of open and unicode instead of str:

# -*- coding: utf-8 -*-
import codecs
outFile = codecs.open('./myFile.txt', 'wb', 'utf-8')
outFile.write(u"●")
outFile.close()

In Python 3, pass the encoding keyword argument to open:

# -*- coding: utf-8 -*-
outFile = open('./myFile.txt', 'w', encoding='utf-8')
outFile.write("●")
outFile.close()
like image 20
Elektito Avatar answered Nov 05 '22 10:11

Elektito