Check whether string is in CSV

后端 未结 4 1345
死守一世寂寞
死守一世寂寞 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"
    
    0 讨论(0)
  • 2021-02-01 19:51
    import csv
    scoresList=[]
    with open ("playerScores_v2.txt") as csvfile:
               scores=csv.reader(csvfile, delimiter= ",")
               for row in scores:
                  scoresList.append(row)
    
    
    playername=input("Enter the player name you would like the score for:")
    print("{0:40} {1:10} {2:10}".format("Name","Level","Score"))
    
    for i in range(0,len(scoresList)):
       print("{0:40} {1:10} {2:10}".format(scoresList[i] [0],scoresList[i] [1], scoresList[i] [2]))
    
    0 讨论(0)
  • 2021-02-01 20:03

    You should have a look at the csv module in python.

    is_in_file = False
    with open('my_file.csv', 'rb') as csvfile:
        my_content = csv.reader(csvfile, delimiter=',')
        for row in my_content:
            if username in row:
                is_in_file = True
    print is_in_file
    

    It assumes that your delimiter is a comma (replace with the your delimiter. Note that username must be defined previously. Also change the name of the file. The code loops through all the lines in the CSV file. row a list of string containing each element of your row. For example, if you have this in your CSV file: Joe,Peter,Michel the row will be ['Joe', 'Peter', 'Michel']. Then you can check if your username is in that list.

    0 讨论(0)
  • 2021-02-01 20:11
    #!/usr/bin/python
    import csv
    
    with open('my.csv', 'r') as f:
        lines = f.readlines()
        cnt = 0
    
        for entry in lines:
            if 'foo' in entry:
                cnt += 1
    
        print"No of foo entry Count :".ljust(20, '.'), cnt
    
    0 讨论(0)
提交回复
热议问题