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

问题描述 投票:0回答:1

在我的项目中,我正在动态地将样式写入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'
python python-3.x
1个回答
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"))

因为目前它是字节类型

© www.soinside.com 2019 - 2024. All rights reserved.