TypeError:write()参数必须为str,而不是HTTPResponse

问题描述 投票:-1回答:2

我目前正在努力为如何在编程类中为最终项目编写密码生成器奠定基础。当前给我带来问题的代码区域如下:

`if not isfile('words.txt'):
    print('Downloading words.txt ...')
    url=str('https://raw.githubusercontent.com/dwyl/english-words/master/words.txt')
    with open('words.txt', 'w') as f:
        f.write(urlopen(url)).read()`

[在一个朋友的帮助下,我们决定使用'brute force'url获得str()。我收到的错误消息暗示我需要将write()放入str(),但是这样做会导致错误,

'io.TextIOWrapper'对象没有属性'str'

。这最初是用Python 2编写的,但是,除了上面的代码块,我设法使所有功能都可以在Python 3.8.0中工作。预先感谢您的协助。

python python-3.x
2个回答
0
投票

使用中

f.write(urlopen(url)).read()

您正在尝试读取文件f

尝试使用

f.write(urlopen(url).read())

-1
投票

urlopen返回httpresponse对象,而不是字符串。您只能将字符串或字节写入文件,而不能写入任意对象。您可以像这样使用该对象(read()返回字节,如果需要字符串,则必须对其进行解码)

with urlopen(url) as resp:
  print(resp.read().decode('utf-8'))

因此,为了使您的代码正常工作-

with open('words.txt', 'w') as f:
    with urlopen(url) as resp:
        f.write(resp.read().decode('utf-8'))
© www.soinside.com 2019 - 2024. All rights reserved.