skysoft999
skysoft999

Reputation: 579

TypeError: a bytes-like object is required, not 'str' python3

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'

Upvotes: 0

Views: 2378

Answers (1)

johnII
johnII

Reputation: 1433

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

Upvotes: 2

Related Questions