简体   繁体   中英

Compare a list and a file for match in python

I want to loop over each element in a List and check if that element matches any of the products in the text file. I have done this:

print("Opening a file")
pro_file = open("inventory.txt", "r")   #open text file for reading

#print(pro_file.read())    #read text file line by line
productList = ['chips', 'biscuits', 'pasta', 'cheese', 'bread', 'rice', 'honey', 'butter', 'cake', 'salt'];

for key in productList:
    for line in pro_file.readlines():
        if key in line:
            print("found" + key)

The nested for loops are only giving the match of first item in the productList. I have stated learning python few days back, so any help would be appreciated.

The first time you call pro_file.readlines() , you reach the end of the file. The second time you call it, there is nothing more to read.

Just read the file once:

with open("inventory.txt", "r") as f:
    pro_file = f.readlines()

then loop the pro_file list

for key in productList:
    for line in pro_file:
        if key in line:
            print("found" + key)

However if you just want to know if one of

productList = ['chips', 'biscuits', 'pasta', 'cheese', 'bread', 'rice', 'honey', 'butter', 'cake', 'salt'];

is in pro_file and you don't care where it is, you can simplify the above code in the following way:

for key in productList:
    if key in pro_file:
        print("found" + key)

The problem is that once you call readlines(), the end of file is reached and the next time you call it on the same open file, it won't return anything. A quick fix would be to just swap the two for statements like this:

for line in pro_file.readlines():
    for key in productList:

However, this will have problems with a large file since readlines() creates a list of all lines in the file and stores that in memory. So, you could try this. I've added comments to explain some of the other changes.

# Per PEP8, variable names should be all lower case with underscores between words
product_list = ['chips', 'biscuits', 'pasta', 'cheese', 'bread', 'rice', 'honey', 'butter', 'cake', 'salt'];

# This is a context manager. It will ensure the file is closed when the code block is finished
# No need to include 'r' when opening a text file as read-only. It's the default.
with open("inventory.txt") as pro_file:
    for this_line in pro_file:
        # A text file can be iterated through one line at a time this way, without loading everything into memory
        for product in product_list:
            if product in this_line:
                # Using format is cleaner and easier to read than + and will work even if the value is a number
                print('Found: {}'.format(product))
                # Since you found a product, you can stop checking products. Break will stop the for product loop.
                break
        else:  # no break
            # What the heck is this? An else in a for loop?
            # In Python, this means "do this if you didn't hit a break statement," and it's very useful.
            # I usually add the comment "no break" after it so it's a little more clear that it was intentional.
            print('Did not find any products in this line')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM