0

Code:

MyTextFile.write("⚡")

Error:

UnicodeEncodeError: 'charmap' codec can't encode character '\u26a1' in position 0: character maps to <undefined>

The emoji 1.4.2 library won't work here because what I am doing is getting some text data from a website and storing it in a text file, and some of the text has emojis. I also don't want to use UTF-8 encoding because it will just turn the emojis into a bunch of text.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Eskimo868
  • 238
  • 1
  • 12
  • 3
    Encode the text first, then write it to a file. When you are ready to use it, decode it – Cfomodz Aug 23 '21 at 16:49
  • 1
    Please provide a [mcve]. I cannot recreate your error because of an undefined variable name. – Code-Apprentice Aug 23 '21 at 16:53
  • Does this answer your question? [UnicodeEncodeError: 'charmap' codec can't encode characters](https://stackoverflow.com/questions/27092833/unicodeencodeerror-charmap-codec-cant-encode-characters) – Tomerikoo Aug 23 '21 at 16:58
  • 3
    "I also don't want to use UTF-8 encoding". You *always* encode text when writing to a file and UTF-8 support emojis (as well as UTF-16 and UTF-32). "it will just turn the emojis into a bunch of text". No, it will turn it into bytes, which is the job of an encoding. If you *decode* the bytes with the wrong encoding, *then* it doesn't look correct. Read [this](https://nedbatchelder.com/text/unipain/unipain.html). – Mark Tolonen Aug 23 '21 at 17:04
  • Are you using Windows, perhaps (whose default character encoding is 8-bit only, I think)? – chepner Aug 23 '21 at 17:08

2 Answers2

1

When you create the file object, specify the encoding you want to use rather than relying on the default.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

You should specify the encoding like:

   with open("/tmp/mytextfile", "w", encoding="utf-8") as mytextfile:
        mytextfile.write("⚡")
        mytextfile.write("\n")
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134