简体   繁体   English

TypeError:类型为“ _csv.writer”的对象没有len()

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

I'm trying to write csv file and return them in a response body but I'm getting 我正在尝试编写csv文件并在响应正文中返回它们,但我正在

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. 我不明白这个错误。

Your problem lies in how you are calling the CSV writer object as mentioned in the comments. 您的问题在于注释中提到的如何调用CSV writer对象。 You should open your new csv file using a "with" statement, this ensures that it closes when you are finished. 您应使用“ with”语句打开新的csv文件,以确保完成后将其关闭。 Your csv file was not designated as a *.csv file (missing the period). 您的csv文件未指定为* .csv文件(缺少句点)。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM