Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将urllib响应写入文件_Python_Python 3.x - Fatal编程技术网

Python 如何将urllib响应写入文件

Python 如何将urllib响应写入文件,python,python-3.x,Python,Python 3.x,我正在尝试将响应写入文件,但无法写入,因为它以字节为单位。有办法吗 我尝试添加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':

我正在尝试将响应写入文件,但无法写入,因为它以字节为单位。有办法吗

我尝试添加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
请输入域:site.google.com
回溯(最近一次呼叫最后一次):
文件“/Users/thnh/Library/Preferences/PyCharmCE2018.2/scratches/URL request test.py”,第13行,在
d、 写(行)
TypeError:write()参数必须是str,而不是bytes

您可以改为以二进制模式打开文件:

with open("domainlist.txt", mode="wb") as d:
    d.write(res.read())

这么简单的事谢谢你@blhsing