bugnet17
bugnet17

Reputation: 181

TypeError: unsupported operand type(s) for %: 'file' and 'str'

I'm trying to download a binary file and save it as its original name on the disk.

I got the next error:

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)

Upvotes: 1

Views: 539

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476554

You can not write:

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

since at that moment open(..)has been evaluated into a file handler. Here you thus basically write code that should evaluate the file handler modulo a string, and then enter this context manager.

You need to do the formatting at the string level, so:

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

Upvotes: 2

Related Questions