Python Forum
Writing emojis to file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Writing emojis to file (/thread-7557.html)



Writing emojis to file - alex36540 - Jan-16-2018

Hello, I am dealing with data that involves emojis and I would like to write them to a file. The data does not come from inside the python editor, I receive it as a JSON response. I am putting the 'emoji' data in a variable for simplicity's sake. Here are a couple ways I've tried:
data = {'string': 'wow, really cool (insert emoji here)'}
data_file = open('file_name.txt','w')
data_file.write(str(data))
This returns the following error:
Error:
UnicodeEncodeError: 'charmap' codec can't encode characters in position xx-xx: character maps to <undefined>
Here is the second way I tried:
data = {'string': 'wow, really cool (insert emoji here)'}
data_file = open('file_name.txt','w')
data_to_string = str(data)
data_file.write(str(data_to_string.encode('unicode-escape'))) #this codec was the only one I could find that supported emojis
But when I opened the file, the data was as such:
b'{\'string\': \'wow, really cool (encoding for emoji)\'}'

I would like to do operations on the dictionary within the file, so that's not optimal. Also, I don't really care about the emoji. Is there any way I could either delete the emoji once I come across it/ ignore it, or is there a codec that will keep the dictionary formatted correctly while not returning an error for the emoji?


RE: Writing emojis to file - wavic - Jan-16-2018

Store the data as JSON file.

import json

data = {'string': 'wow, really cool (insert emoji here)'}

# save the data
with open('my_data.json', 'w') as out_f:
    json.dump(data, out_f)

# load the data
with open('my_data.json', 'r') as in_f:
    data = json.load(in_f)
Ref: https://docs.python.org/3/library/json.html