【发布时间】:2018-05-16 00:04:52
【问题描述】:
我有一个包含 5 列和 3 行的 csv 文件。列由制表符分隔,行由新行分隔。有些元素是空的。我必须找到所有行都为空的列。文件在这里:
我的代码如下。问题是它不适用于最后一列,即如果最后一列为空,或者该行中最后一个制表符之后的最后一列中没有值,它仍被视为非空字符串。我检查了“eachElement”的长度,奇怪的是,第一行和第二行的长度显示为 1,但第三行显示为空字符串。似乎它在前两行的最后一列中的最后一个选项卡之后计算新行(因此长度为 1),但从逻辑上讲它不应该因为我使用了“内容中的行”。所以每一行应该只包含没有“\n”的那一行
import sys
import array
rowIndex = -1
countEmptyCol = array.array('i',(0 for i in range(0,5))) #this creates an unsigned int array of 58 elements and assigns 0 for each
listEmptyColumns = [] #contains index of columns that are empty for all records
#Get number of empty values for each columns in the array
with open("D:\TU Ilmenau\L1T2\Labs\DDM\Python\database.csv", "r", 1) as file:
content = file.readlines()
for line in content:
rowIndex += 1
colIndex = -1
for eachElement in line.split("\t"):
colIndex += 1
if not eachElement:
#increases the value of index by 1
countEmptyCol.insert(colIndex, countEmptyCol.pop(colIndex) + 1)
numOfRows = rowIndex + 1
#Compare if number of empty values for each column is equal to the number of total rows
for idx, val in enumerate(countEmptyCol):
if val == numOfRows:
listEmptyColumns.append(idx)
print listEmptyColumns
【问题讨论】:
-
你真的应该使用像
csv.reader()- docs.python.org/2/library/csv.html这样的csv解析器 -
你为什么认为它没有
'\n'(提示:它确实包括'\n')?注意:你可以在没有readlines()的情况下使用for line in file:。如果这不是家庭作业,那么您可以使用pandas,这将使这个问题变得轻而易举。