python inserting variable string as file name

And with the new string formatting method...

f = open('{0}.csv'.format(name), 'wb')

You need to put % name straight after the string:

f = open('%s.csv' % name, 'wb')

The reason your code doesn't work is because you are trying to % a file, which isn't string formatting, and is also invalid.


you can do something like

filename = "%s.csv" % name
f = open(filename , 'wb')

or f = open('%s.csv' % name, 'wb')


Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance

f = open('{}.csv'.format(name), 'wb')

Another option - the f-string formatting (ref):

f = open(f"{name}.csv", 'wb')