尝试读取 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
我该如何解决?
最佳答案
好吧,在阅读了您的代码后,我的第一 react 是天啊!他打开那个可怜的文件有多少?
这是你类(class)的新版本
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()
或.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,是全局python的属性组合 文件
类。
所以 File
对象不是 file
的实例,但它有一个兼容的接口(interface)。因此,在前面的代码中我测试了self.file
是否是一个str
,那么它应该是我们open()
的路径所以我们得到一个 file()
并解析它。否则,self.file
是一个File
对象或一个file()
对象,我们只需要解析它。如果两者都不是,那么这是一个错误,我们将除外。
关于python - 找到错误 CSV : coercing to Unicode: need string or buffer, S3BotoStorageFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17316374/