TypeError:%不支持的操作数类型:“文件”和“ STR”

时间:2018-11-05 11:38:13

标签: python

我正在尝试下载一个二进制文件并将其保存为磁盘上的原始名称。

我遇到下一个错误:

with open('%s.bin', 'wb') %name as f:
TypeError: unsupported operand type(s) for %: 'file' and 'str'
import requests

f = open('test.txt')
tool = f.read().splitlines()
f.close()

params = {'apikey': 'XXXXXXXXXX', 'hash': (tool)}
response = requests.get('https://www.test.com/file/download', params=params)

name = response.headers['x-goog-generation']
downloaded_file = response.content

if response.status_code == 200:
    with open('%s.bin', 'wb') %name as f:
        f.write(response.content)

1 个答案:

答案 0 :(得分:2)

您不能写:

with open('%s.bin', 'wb') % name as f:

从那时起open(..)已被评估为文件处理程序。因此,您在这里基本上编写了代码,该代码应评估文件处理程序 modulo 一个字符串,然后输入此上下文管理器。

您需要在字符串级别进行格式化,所以:

if response.status_code == 200:
    with open('%s.bin' % name, 'wb') as f:
        f.write(response.content)