TypeError:需要类似字节的对象,而不是' str' python3

时间:2017-12-28 11:30:19

标签: python python-3.x

在我的项目中,我动态地将样式写入HTML文件。我最近从python2迁移到3.现在它抛出了一个错误,如下所示:

代码段:

 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>')

错误日志:

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'

1 个答案:

答案 0 :(得分:2)

如何更改

uploaded_file + '.html', "wb")

uploaded_file + '.html', "w")

然后你需要转换下面的行

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

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

因为目前它是字节