Write playing card symbols to text file

I have to write playing card symbols (Spades, Hearts, Diamonds, Clubs) into a text file. I know their unicode values (2660, 2665, 2666, 2663) and the print command displays them correctly on the screen, but write to file gives an error.
I’ve written a small piece of code to demonstrate the problem:
OutFile = “Mod.txt”
Out = open(OutFile,“w”)
Spades = ‘\u2660’
Line = “Spades= {}”.format(Spades)
print(Spades)
print(Line)
Out.write(Line)
Out.close()

Write to screen is ok:
:spade_suit:
Spades= :spade_suit:

But write to file gives an error:
Traceback (most recent call last):
File “C:\Users\tmind\Development\Python\Probeersels\utf.py”, line 9, in
Out.write(Line)
File “C:\Users\tmind\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py”, line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: ‘charmap’ codec can’t encode character ‘\u2660’ in position 8: character maps to

Any help will be appreciated. Regards, Tom

You’ll need to specify a file encoding that can support extended
Unicode characters, such as UTF-8. Try:

Out = open(OutFile, "w", encoding="utf-8")
1 Like

Thank you very much. That did it!

I believe this is going to be the default in 3.15, still annoying how Windows uses CP-1252/Latin1 as the default encoding. That’s messed me up a ton when I forget to specify encoding somewhere then suddenly the 2 emojis in my text stream become random wingdings.

1 Like

Thank you for your reply. I am at Python 3.10 so that explains it.

Regards, Tom