首页 > 解决方案 > 程序只读取 csv 文件的第一行

问题描述

好的,基本上我有两行数据

name    tribe   id  Air Water   Earth   Fire
Pema    Xero    X14C    24  54  34  43
Otaku   Taru    T111F   54  78  65  78

目前,我的代码根据某些条件检查列“id”是否有错误,但我的代码只读取第一行(Pema 的行)并停止。我不知道是什么原因造成的,任何解决此问题的帮助将不胜感激。

import csv
filePath ="data3.csv"


length="Length of Avatar ID is not 5 "
name_tribe= "Invalid first letter"
score_grade="Invalid last letter"
mid_integers="Invalid integers"

def isValidAvatarIDFormat():
    with open(filePath) as csvfile:
        reader = csv.DictReader(csvfile)
        remarks=[] 
        for row in reader:

            if(len(row['id'])!=5):
                remarks.append(length)


            if(row['tribe'][0] != row['id'][0]):
                remarks.append (name_tribe)


            avg_score= 0
            user,tribe,id, *scores= row.values()
            if all(score.isdigit() for score in scores):
                average= sum([int(score) for score in scores])/4
                if (average >=80):
                    avg_score="A"
                elif (average >=70 and average <80):
                    avg_score="B"
                elif (average >=60 and average <70):
                    avg_score="C"
                elif (average >=50 and average <60):
                   avg_score="D"                    
                elif (average >=40 and average <50):
                   avg_score="E"
                else:
                    avg_score="F"
            if(avg_score != row['id'][-1]):
                    remarks.append (score_grade)


            if (row['id'][1].isdigit() and row['id'][2].isdigit() and row['id'][3].isdigit()):
                    continue
            else:
                remarks.append (mid_integers)

            if (len(remarks) == 1):
                print (remarks)
            elif (len(remarks) >1):
                for i in range(0, len(remarks)):
                    print(remarks[i])

            del remarks 
            remarks =[]           


print("{0:<10}{1:^18}{2:^15}".format("Avatar Name  |","Avatar ID |","Comments"))        
isValidAvatarIDFormat()

标签: python

解决方案


以下条件:

if (row['id'][1].isdigit() and row['id'][2].isdigit() and row['id'][3].isdigit()):
    continue

在您的关键for循环中使其跳过一行,该id行的值在选定位置有数字(就像它发生的那样 value T111F

T111F- 位置 1,2 和 3 中的符号 - 是数字,这使得循环使用continue运算符跳过迭代。

您的案例与行位置无关,而是与id列的选定位置中的特定符号有关。


推荐阅读