在python

时间:2018-05-08 20:00:01

标签: python

我想循环遍历List中的每个元素,并检查该元素是否与文本文件中的任何产品匹配。我这样做了:

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)

嵌套for循环仅提供productList中第一项的匹配。几天前我已经说过学习python,所以任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:2)

第一次拨打pro_file.readlines()时,您会到达文件的末尾。你第二次打电话,没有什么可读的了。

只需阅读一次文件:

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

然后循环pro_file列表

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

但是如果你只是想知道其中一个

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

pro_file,你不在乎它在哪里,你可以用以下方式简化上面的代码:

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

答案 1 :(得分:1)

问题是,一旦调用readlines(),就会到达文件末尾,下次在同一个打开的文件上调用它时,它不会返回任何内容。快速修复就是将这两个语句交换为这样的语句:

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

但是,这会导致大文件出现问题,因为readlines()会创建文件中所有行的列表并将其存储在内存中。所以,你可以试试这个。我添加了评论来解释其他一些变化。

# 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')