open('%r.csv', 'wb') % names[q]
should be open('%r.csv' % names[q], 'wb')
.
In the former case you are opening a file named "%r.csv" for writing in binary mode and then attempting to modulo the file object with the contents of names[q]
. file
objects do not support the modulo operator and so you get the TypeError
.
In the latter case we are invoking the format
method of the string %r.csv
with the module operator resulting in a string that is passed to the open
function.
As an aside, you may want to consider another way of associating names to data - you could store names alongside your data in either tuples, dictionaries or class instances:
# Tuples
data = [("cat", [1, 2, 3, 4]), ("dog", [5, 6, 7])]
for name, file_data in data:
print name, "=>", file_data
# Dictionary (assumes only one instance of name per data point)
data = {"cat": [1, 2, 3, 4], "dog": [5, 6, 7]}
for name, file_data in data.items():
print name, "=>", file_data
# Class instances (ignore this one if you haven't done any OO before)
# (You don't need it if you don't *know* you need it).
class MyDataType(object):
def __init__(self, name, data):
self.name = name
self.data = data
data = [MyDataType("cat", [1, 2, 3, 4]), MyDataType("dog", [5, 6, 7])]
for data_point in data:
print data_point.name, "=>", data_point.data