Check whether string is in CSV

后端 未结 4 1350
死守一世寂寞
死守一世寂寞 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 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.

提交回复
热议问题