-1

I have the following line of code inside a loop that goes through the records of a database table and print out the comment field:

output_file.write("\nTimesheet comment: {}".encode('utf-8').format(timesheet.comments))

it gives the following error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 570: ordinal not in range(128)

The output file also print the following "^M" in several lines. How can I fix this error. Even ignoring strange characters could be an acceptable solution if there is no simple way to go round the error but I don't know how to attach a condition to a .format(...) function

Dino
  • 1,307
  • 2
  • 16
  • 47

1 Answers1

0

I can't reproduce your error!

If you do;

.encode('utf-8').format(...)

then you are first converting the string to a "bytes" object, which has no ".format()" method, meaning you will get an AttributeError.

If you do like this;

with open('some_file_name.txt', 'wb+') as output_file:
...     output_file.write("\nTimesheet comment: {}".format(u'\xa3').encode('utf-8'))
... 
with open('some_file_name.txt', 'r') as output_file:
...     print(output_file.read())
... 
Timesheet comment: £

It works just fine for me..

In other words; I am not able to reproduce your error, you need to elaborate if I (or anyone) is going to help you.

Vinzent
  • 1,070
  • 1
  • 9
  • 14