1

尝试读取CSV的数和数时出现以下错误:

> 强制转换为 Unicode:需要字符串或缓冲区,找到 S3BotoStorageFile

import csv

class CSV:
    def __init__(self, file=None):
        self.file = file

    def read_file(self):
        data = []
        file_read = read_file(self.file)
        return file_read

    def get_row_count(self):
        return len(self.read_file())

    def get_column_count(self):
        new_data = self.read_file()
        return len(new_data[0])

    def get_data(self, rows=1):
        data = self.read_file()
        return data[:rows]

def read_file(self):
    with open(self.file, 'r') as f:
        data = [row for row in csv.reader(f.read().splitlines())]
    return data

我该如何解决?

4

1 回答 1

4

好吧,在阅读了您的代码后,我的第一反应是 OMG!他打开那个可怜的文件有多少?

这是您的课程的新版本

class CSV:
    def __init__(self, file=None):
        self.file = file
        with open(self.file, 'r') as f:
            self.data = [row for row in csv.reader(f)]

    def get_row_count(self):
        return len(self.data)

    def get_column_count(self):
        return len(self.data[0])

    def get_data(self, rows=1):
        return self.data

我还修复了你的csv.reader()处理方式。它接受一个文件对象,不需要.read()or .read().splitlines(),它只会导致错误。这可能是它失败的原因。

好的,从您所说的来看,您正在使用 AWS,并且您的文件不是文件的字符串路径,而是已经是文件对象。所以你不需要这个open()部分。您可能需要修改代码,如下所示:

class CSV:
    def __init__(self, f=None):
        self.file = f
        if isinstance(self.file, str): # if the file is a string, it's a path that has to be opened
            with open(self.file, 'r') as f:
                self.data = [row for row in csv.reader(f)]
        elif isinstance(self.file, File) or isinstance(self.file, file): # if that's a file object, no need to open
            self.data = [row for row in csv.reader(self.file)]
        else: # otherwise, I don't know what to do, so aaaaaaaargh!
            raise Exception("File object type unknown: %s %s" % (type(file), file,))

    def get_row_count(self):
        return len(self.data)

    def get_column_count(self):
        return len(self.data[0])

    def get_data(self, rows=1):
        return self.data

读取S3BotoStorage.py,S3BotoStorage类继承自django.core.files.base.File,django.core.files.utils.FileProxyMixin是全局pythonfile类的属性组合。

所以一个File对象不是 的实例file,但它有一个兼容的接口。因此,在前面的代码中,我测试了 a 是否self.file是 a str,那么它应该是open()我们得到 afile()并解析它的路径。否则,self.file是一个File对象或一个file()对象,我们只需要解析它。如果两者都不是,那么这是一个错误,我们将排除。

于 2013-06-26T09:37:46.867 回答