TypeError: object of type '_csv.writer' has no len()

1k views Asked by At

I'm trying to write csv file and return them in a response body but I'm getting

TypeError: object of type '_csv.writer' has no len()

Below is my code:

class LogCSV(object):
    """CSV generator.

    This class responds to  GET methods.
    """
    def on_get(self, req, resp):
        """Generates CSV for log."""

        mylist = [
            'test','one'
        ]

        myfile = open('testingcsv', 'w')
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(mylist)

        resp.status = falcon.HTTP_200
        resp.content_type = 'text/csv'
        resp.body = (wr)

I don't understand the error.

1

There are 1 answers

0
Nanook On BEST ANSWER

Your problem lies in how you are calling the CSV writer object as mentioned in the comments. You should open your new csv file using a "with" statement, this ensures that it closes when you are finished. Your csv file was not designated as a *.csv file (missing the period). You could also set it all up as a method where your list is passed into the method instead of created within the method.

I hope these suggestions help.

def on_get(filename, retrievedData) :
    with open(filename, 'w') as csvfile:
        dataWriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        dataWriter.writerow(retrievedData)

retrievedData = ['test','one']

on_get('testing.csv', retrievedData)