[英]Compare a list and a file for match in python
我想遍歷列表中的每個元素,並檢查該元素是否與文本文件中的任何產品匹配。 我已經做到了:
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,所以任何幫助將不勝感激。
第一次調用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)
問題在於,一旦您調用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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.