Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writing emojis to file
#1
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?
Reply
#2
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,388 Sep-27-2022, 01:38 PM
Last Post: buran
  Writing to json file ebolisa 1 1,014 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Writing to External File DaveG 9 2,509 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  Writing to file ends incorrectly project_science 4 2,704 Jan-06-2021, 06:39 PM
Last Post: bowlofred
  Writing unit test results into a text file ateestructural 3 4,775 Nov-15-2020, 05:41 PM
Last Post: ateestructural
  Writing to file in a specific folder evapa8f 5 3,446 Nov-13-2020, 10:10 PM
Last Post: deanhystad
  Failure in writing binary text to file Gigux 7 3,828 Jul-04-2020, 08:41 AM
Last Post: Gigux
  writing data to a csv-file apollo 1 2,380 Jul-03-2020, 02:28 PM
Last Post: DeaD_EyE
  Writing to File Issue Flash_Stang 3 2,537 Jun-05-2020, 05:14 AM
Last Post: Gribouillis
  Help! Formatting and Writing to a File bwdu 2 2,419 Apr-19-2020, 09:29 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020