Search code examples
pythoncsvcsvreader

How to break csv reader loop after the first condition is met?


with open("ten.csv", 'rb') as f:
  reader = cs.DictReader(f)
  
  for row in reader:
    for i in range(len(list_of_column_names[0])):
      if isPhoneNumber(str(row[list_of_column_names[0][i]])) == True:
        print(row[list_of_column_names[0][i]])
        break

csv looks like
id,first_name,last_name,email,gender,dob,street,city,zip,state,drivers_license,phone,userid,ssn
1,Nanon,le Keux,[email protected],Female,4/25/2020,0 Blaine Trail,Charlotte,11111,NC,646144685,704-435-8128,1111122,123-45-6789
2,Brewster,Dagnall,[email protected],Male,2/27/2014,8 Farwell Point,Montgomery,11111,AL,146790405,334-133-5888,1111122,234-56-7890
3,Eirena,Whyborne,[email protected],Female,9/16/1996,2120 Dexter Court,Washington,11111,DC,6732768794,202-558-7854,1111122,345-67-8901
4,Kippy,Sterndale,[email protected],Male,7/19/1965,61 Northwestern Place,Naples,11111,FL,7202285517,941-380-3634,1111122,456-78-9012
5,Creigh,Bleckly,[email protected],Male,10/29/1997,63151 Prairie Rose Circle,Tampa,11111,FL,9060794486,813-210-7870,1111122,567-89-0123
6,Caleb,Feldbaum,[email protected],Male,10/23/1962,738 American Ash Park,Birmingham,11111,AL,5049418992,205-767-9467,1111122,678-90-1234
7,Luisa,Reeder,[email protected],Female,9/3/2014,81399 Karstens Pass,Miami,11111,FL,3476652874,305-531-4287,1111122,789-01-2345
8,Bondon,Copper,[email protected],Male,1/9/1975,4439 Goodland Circle,Cincinnati,11111,OH,9573026686,513-966-8317,1111122,890-12-2344
9,Hedi,Aleksankov,[email protected],Female,4/24/2021,4 Union Drive,Green Bay,11111,WI,5202059280,920-509-9672,1111122,901-23-4567
10,Uriah,Dunphie,[email protected],Male,2/4/2010,73 Hagan Hill,Bronx,11111,NY,8393306353,718-578-5726,1111122,012-34-5678

The code return all the phone numbers in the csv file. I want it to stop after it gets the first number. Thats what the break is there for. But it just keeps going.


Solution

  • It is because there two loops: one for 'row in reader', one for 'i in range'.
    To completely go out of all loops, you should use two breaks and a flag.

    flag = False
    for row in reader:
        if flag:
          break
        for i in range(len(list_of_column_names[0])):
          if isPhoneNumber(str(row[list_of_column_names[0][i]])) == True:
            flag = True
            print(row[list_of_column_names[0][i]])
            break