python - 从文件或嵌套列表中删除空行

标签 python

我有一个 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/

相关文章:

python - 如何将 Python 原生数据结构存储到文件中或从文件中检索?

python - PostgreSQL 错误-psql : fe_sendauth: no password supplied

python - 如何在 Django 管理表单中添加自定义操作按钮并发布信息

python - 更新 django 项目、跟踪更新的最佳方法

python - PIP3 列表完全失败并返回错误

python - 使用 pandas.to_datetime 转换 None 值是不可预测的

javascript - Flask-SocketIO 没有收到消息

python - Tkinter : Getting screen text unit width.(不是像素)

python - c++中的两个比较运算符,如python

python - list_display 不起作用