首页 > 解决方案 > What is not a row in a csv file?

问题描述

I came upon this code in a tutorial:

 for row in csv_reader:
        if not row:
            continue
        dataset.append(row)

Which I take to mean that if the code encounters something other than a row, just skip and continue. Is that correct?

What defines 'not row'?

标签: pythonrowload-csv

解决方案


row在这种情况下只是一个变量名。当您这样做时if row,您实际上是在检查 python 认为的变量是否有任何内容True

看看Patrick Haugh 的这个答案Falsy,他在其中重点介绍了 python 中的许多示例。

用一个最小的例子来说明:

import csv
for row in csv.reader(['row1,foo','', 'row3,bar']):
    print(row)

产量

['row1', 'foo']
[]
['row3', 'bar']

但如果你这样做

for row in csv.reader(['row1,foo','', 'row3,bar']):
    if row:
        print(row)

然后输出是

['row1', 'foo']
['row3', 'bar']

因此基本上空行被过滤掉了。


推荐阅读