每一个人。
我无法找到一种pythonic方法来忽略CSV中的“空白”行。我使用引号,因为我说的是看起来像'','','','',''的行。这是一个CSV(空行可以是随机的):
id,name,age
1,alex,22
3,tiff,42
,,
,,
4,john,24
这是代码:
def getDataFromCsv(path):
dataSet = []
with open(unicode(path), 'r') as stream:
reader = csv.reader(stream, delimiter=',')
reader.next() # ignoring header
for rowdata in reader:
# how to check here?
dataSet.append(rowdata)
return dataSet
以下是我一直在阅读的类似问题,但特别是与此不同:python csv reader ignore blank row
您可以使用any
检查行中的任何列是否包含数据:
for rowdata in reader:
# how to check here?
if any(x.strip() for x in rowdata):
dataSet.append(rowdata)
关于什么:
if len(rowdata) > 0:
dataSet.append(rowdata)
或者我错过了你问题的一部分?
你可以使用内置函数any
:
for rowdata in reader:
# how to check here?
if not any(row):
continue
dataSet.append(rowdata)
with open(fn, 'r') as csvfile: reader = csv.reader(csvfile) data = [row for row in reader if any(col for col in row)]