Check whether string is in CSV

后端 未结 4 1347
死守一世寂寞
死守一世寂寞 2021-02-01 19:23

I want to search a CSV file and print either True or False, depending on whether or not I found the string. However, I\'m running into the problem wher

4条回答
  •  温柔的废话
    2021-02-01 19:51

    when you look inside a csv file using the csv module, it will return each row as a list of columns. So if you want to lookup your string, you should modify your code as such:

    import csv
    
    username = input()
    
    with open('Users.csv', 'rt') as f:
         reader = csv.reader(f, delimiter=',') # good point by @paco
         for row in reader:
              for field in row:
                  if field == username:
                      print "is in file"
    

    but as it is a csv file, you might expect the username to be at a given column:

    with open('Users.csv', 'rt') as f:
         reader = csv.reader(f, delimiter=',')
         for row in reader:
              if username == row[2]: # if the username shall be on column 3 (-> index 2)
                  print "is in file"
    

提交回复
热议问题