S
S
sortfact3332021-10-31 13:14:40
Python
sortfact333, 2021-10-31 13:14:40

How to fix an error while creating a file?

I'm trying to create a file from text that I store in the variable text

text='.......Текст файла'
dir = r"D:\Work\Project\test\object.gltf"
file = open(dir, 'w+')
file.write(text)
file.close()

At first everything worked fine, but one file causes an error.

Traceback (most recent call last):
File "generate.py", line 101204, in
file.write(text)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\encodings\cp1251. py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 821-824: character maps to

When I directly copy the text of the file and create object.gltf, everything works fine.
The file contains Japanese characters. Maybe it's somehow related.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-10-31
@sortfact333

If the text can contain Unicode, then you need to set the encoding when opening the file, for example, encoding='utf-8'. See open() .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question