Question

I have a dictionary where item_dictionary[0] corresponds to data[0], and item_dictionary[1] corresponds to data[1].

item_dictionary = {'10350':'cat', '560':'dog'}
names = item_dictionary.values()

data = [[1, 2, 3, 4], [5, 6, 7]]

I tried to write the items in data[0] and data[1] to different .csv files like this:

def writer(item):
    q = data.index(item)    
    myfile = open('%r.csv', 'wb') % names[q]
    wr = csv.writer(myfile)
    wr.writerows(data[q])
    myfile.close()

z = [writer(x) for x in data]

This returns the error:

Traceback (most recent call last):
File "", line 1, in
File "", line 3, in writer
TypeError: unsupported operand type(s) for %: 'file' and 'str'`.

My guess for the 'str' part of the error is that names[q] returns, say, 'cat' instead of cat. However, I don't know what operand type to use instead and don't know how to get around the str problem, so could someone please help me? Thanks.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top