python - 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'?
解决方案
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']
因此基本上空行被过滤掉了。
推荐阅读
- bash - 语法错误:“(”使用 bash 命令创建 openssl 证书时出现意外错误
- apache-spark - Spark-redis:数据帧写入时间太慢
- javascript - JS:仅当所有输入都通过验证时,如何在表单中启用提交按钮
- export - PBI - 导出基础数据想要拥有所有列
- python - 将 jupyter 实验室笔记本转换为脚本,无需在单元格之间添加注释和新行
- python-3.x - 如何在数据框中同时将列和枢轴列值组合到新列中?
- java - 如何为 Spring Boot 应用程序(如 Rake 任务)执行命令行任务?
- gcc - 链接器脚本;向内存区域添加偏移量;
- applescript - Applescript 在多个文件夹中查找最接近给定时间创建的文件
- python - 如何使用苹果 i tunes api 抓取多个页面