我正在尝试将响应写到文件中,但是由于它以字节为单位,所以无法写入。有办法吗?
我尝试添加utf-8或ascii
import urllib.request
domain = input('Please enter domain: ')
url = 'https://api.somesite.com/v2/domain/'+ domain
token = '3fe6465b84f94cexxx'
req = urllib.request.Request(url, None, {'X-RFToken': token})
res = urllib.request.urlopen(req)
for line in res:
d = open("domainlist.txt", mode="wt")
d.write(line)
错误:
Please enter domain: site.google.com
Traceback (most recent call last):
File "/Users/thnh/Library/Preferences/PyCharmCE2018.2/scratches/URL request test.py", line 13, in <module>
d.write(line)
TypeError: write() argument must be str, not bytes
答案 0 :(得分:0)
您可以改为以二进制模式打开文件:
with open("domainlist.txt", mode="wb") as d:
d.write(res.read())