我有一个 csv 文件,我逐行放入一个空列表中,因此最终结果是一个嵌套列表,其中每一行都在列表中,例如:
[[1.1,2.6,3,0,4.8],[3.5,7.0,8.0]....and so on.....].
问题是文件末尾是空字符串,它们最终出现在最终列表中,例如:
[[1.1,2.6,3,0,4.8],[3.5,7.0,8.0],['','','','','','','','','']]
我如何摆脱这些或阻止它们被附加到列表中。它们是相当大的 csv 文件,所以我宁愿停止将它们附加到初始列表中。我觉得我正在构建一个额外的大列表,而我可能也不需要,这可能会导致内存问题。 这是到目前为止的代码:
csvfile = open(file_path, 'r')
reader = csv.reader(csvfile)
data_list = []
for row in reader:
data_list.append(row)
csvfile.close()
i = 0
file_data = []
while i < len(data_list):
j = 0
while j < len(data_list[i]):
try:
data_list[i][j] = float(data_list[i][j])
except ValueError:
pass
j += 1
file_data.append(data_list[i])
i += 1
print file_data
最佳答案
The problem is at the end of the file are empty strings
您可以决定不附加它们:
for row in reader:
if any(row): # Checks for at least one non-empty field
data_list.append(row)
以下是 any() 函数的工作原理:
>>> any(['132', '', '456'])
True
>>> any(['', '', ''])
False
关于python - 从文件或嵌套列表中删除空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16706929/