0

I have this piece of code in python:

def write_to_log_file(text):
    with open ("C:\Users\Administrator\Desktop\log.txt",mode='w') as file:
        file.write(text)

however when I run this code I am getting the following error:

line 13, in write_to_log_file
    file.write(text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 126: ordinal not in range(128)
ErezN
  • 669
  • 2
  • 13
  • 25
  • Try to encode your unicode string as ascii:`unicodeData.encode('ascii', 'ignore')` –  Aug 24 '17 at 14:17
  • Please show some of the text that you are trying to write. Especially, what format the text is in right now. I expect that your text is unicode and as such needs to be treated differently. – Bas Jansen Aug 24 '17 at 14:17
  • Please check the [documentation](https://docs.python.org/3/library/functions.html#open) on the `open` function and, considering the error message you got, make an educated guess about which additional parameter you need to pass to `open`. – ForceBru Aug 24 '17 at 14:18
  • @BasJansen - this is the code I am using: text = driver.find_element_by_css_selector("div.pe-wp-default:nth-child(2) > p:nth-child(1)").text print text and when I print it to the console this is the text I am getting: We understand that every organization has unique critical data characteristics, so manual policies are not sufficient in today’s world. Through advanced machine learning technologies, we automatically classify sensitive data, enforce data security policy and demonstrate compliance. – ErezN Aug 24 '17 at 14:19
  • We understand that every organization has unique critical data characteristics, so manual policies are not sufficient in today’s world. Through advanced machine learning technologies, we automatically classify sensitive data, enforce data security policy and demonstrate compliance. – ErezN Aug 24 '17 at 14:20
  • @Mandy8055, observe: `'नमस्ते'.encode('ascii', 'ignore') == b""` – ForceBru Aug 24 '17 at 14:20
  • Sorry Sir(@ForceBru) I didn't get that what are you trying to depictt? –  Aug 24 '17 at 14:22
  • @ErezN Look at http://www.fileformat.info/info/unicode/char/2019/index.htm and see if you understand why this is failing. Tip: Think about ASCII versus unicode. – Bas Jansen Aug 24 '17 at 14:22
  • @Mandy8055, this is effectively destroying all non-Unicode data. – ForceBru Aug 24 '17 at 14:22
  • Okay Sir(@ForceBru).Thanks –  Aug 24 '17 at 14:24
  • Please check the answer to this similar question: https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20 – KJP Aug 24 '17 at 14:26

1 Answers1

2

Reference

def write_to_log_file(text):
    with open ("C:\Users\Administrator\Desktop\log.txt",mode='w') as file:
        file.write(text.encode('utf8'))
xtonousou
  • 569
  • 5
  • 16