I want to check if a specific word (user-defined via input) occurs in a csv file. Now, I've come up with a code that does that but since I'm a beginner and don't want to adapt any "bad habits", I'm wondering if it is the fastest, easiest and shortest possibility. Any given improvements are appreciated. sa
This works (mostly, see below), but the whole thing with the "yes" variable makes me think that there has to be a better way to solve this.
def add(self, name): with open(filepath, "r+") as file: csvreader = csv.reader(file, delimiter=",", quotechar='"') csvwriter = csv.writer(file, delimiter=",", quotechar='"') yes = False for line in csvreader: if name in line[0]: yes = True if yes: print("This ingredient has already been added") else: csvwriter.writerow([name]) It sometimes throws an "IndexError: list index out of range". I don not have any idea as to why because it only does that sometimes. Other times it works fine...
breakafteryes = True. No point continuing going through the file. Otherwise, the code looks pretty good to me. If you can't store the file in memory, you're not going to get faster.if line and name in line[0]:if line and [...].delimiterinto tokens, or words.