我想解析一个给定的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]

有没有一个更聪明的,蟒蛇式的解决方案,而不检查行是否为空?一般来说,我更喜欢DictReader

最佳答案

您可以使用空列表的计算结果为break并使用while循环来代替使用false

while(row in reader):
    result+=[row]

07-24 09:52
查看更多