0
votes

I've tried direct string conversions and multiples methods, however, the error keeps on arising.

f.write("Original Price: " + str(original_price) + "/n")
#Where original price is an integer taken through an html source.

The error: f.write("Original Price: " + str(original_price)) File "C:\ProgramData\Anaconda3\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 '\u20b9' in position 16: character maps to

Looking for a method to write this information into my file.

2
that char is rupee. the \u20b9 is rupee. it cannot encode it using unicode i guess. And, also it is \n not /n. - Ozgur Bagci
Why is Python trying to write cp1252; how did you open the file in the first place? - tripleee

2 Answers

1
votes

The write method expects a bytes object; you are trying to pass a str object. You need to encode it first. To write the UTF-8 encoding of the string, for example,

f.write("Original Price: {}\n".format(original_price).encode('utf-8'))

The value of original_price doesn't seem to be an actual number; it contains the symbol for the rupee, , for which there is no equivalent in the character encoding you are trying to use.

1
votes

I found a solution I guess:

You should open file with encoding parameter:

with open('towrite.txt, 'w+', encoding='utf-8') as f:
    f.write('Original Price: ' + str(original_price) + '\n')

This should work.