python - 读取非结构化 CSV

标签 python csv

我想解析给定的 csv 文件,它看起来像

"header_1" ; "header_2"; "header_3"
"a" ; "b" ; "c"
"1" ; "2" ; "3"

Some footer text; maybe more.

Only well and correct structured fields shall be parsed. How can I enforce that?

The following code does the job:

with open(path) as csv_file:
    reader = csv.reader(csv_file, delimiter=";", strict=False)
    result = []
    for row in reader:
        if row == []:
            break
        result += [row]

是否有更智能的 pythonic 解决方案而不检查该行是否为空?一般来说,我更喜欢 DictReader .

最佳答案

除了使用 break,您还可以使用空列表评估为 false 的事实,并使用 while 循环代替:

while row in reader:
    result.append(row)

关于python - 读取非结构化 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43227625/

相关文章:

python - Dragonfly IntegerRef 出现 TypeError : 'NoneType' object is not callable error

javascript - Bokeh:双击圆圈时的JS回调

python - 如何切割和 reshape /融化表格或 CSV 文件

python - 将 CSV 文件导入 MongoDB 时,文件大小要求是否会发生变化?

javascript - 使 URL 在单个 HTML 表列中的 JS 中可点击? (CSV 解析为 HTML 表)

python - 如何让网络应用程序自动下载 mp3 文件 [Google App Engine 上的 Flask]

python - 多进程守护进程不在父退出时终止

.net - 是否可以从Thread.CurrentThread.CurrentCulture获取CSV分隔符? (。净)

python - 将递归与循环相结合以找到最大值

php - 添加 mysql 列以在 csv php 中输出?