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

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()

最佳答案

以下情况:

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


在关键的for循环中,它跳过了id列的值在选定位置具有数字的行(因为值T111F发生了这种情况)

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

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

关于python - 程序仅读取csv文件的第一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56060981/

10-12 20:39