0

In my project, I'm dynamically writing styles into HTML file. I have recently migrated from python2 to 3. Now it's throwing an error as shown below log:

Code Snippet :

 html_text = markdown(html_content, output_format='html4')
    css = const.URL_SCHEME + "://" + request_host + '/static/css/pdf.css'
    css = css.replace('\\', "/")
    # HTML File Output
    #print 'Started Html file generated' + const.CRUMBS_TIMESTAMP
    html_file = open(os.getcwd() + const.MEDIA_UPLOADS + uploaded_file_name + '/output/' +
                     uploaded_file + '.html', "wb")
    #print(html_file)
    html_file.write('<style>')
    html_file.write(urllib.request.urlopen(css).read())
    html_file.write('</style>')

Error Log :

Quit the server with CTRL-BREAK.
('Unexpected error:', <class 'TypeError'>)
Traceback (most recent call last):
  File "C:\Dev\EXE\crumbs_alteryx\alteryx\views.py", line 937, in parser
    result_upload['filename'])
  File "C:\Dev\EXE\crumbs_alteryx\alteryx\views.py", line 767, in generate_html
    html_file.write('<style>')
TypeError: a bytes-like object is required, not 'str'
2
  • It's because you have opened file in write byte mode. what does it to with django? Commented Dec 28, 2017 at 11:53
  • Python 3 makes a clear distinction between bytes strings and text strings. This prevents a lot of sloppy string handling that Python 2 lets you get away with; it also makes Unicode handling a lot saner. It may seem annoying at first, but you'll soon get used to it, and come to appreciate it. Commented Dec 28, 2017 at 12:36

1 Answer 1

2

How about changing your

uploaded_file + '.html', "wb")

to

uploaded_file + '.html', "w")

and then you need to convert your line below

   html_file.write(urllib.request.urlopen(css).read())

to

   html_file.write(urllib.request.urlopen(css).read().decode("utf-8"))

because currently it is type byte

Sign up to request clarification or add additional context in comments.

2 Comments

No change Mr @johnll
Thanks Mr @johnll for your valuable answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.