[英]Iteration with if condition not working in python
我寫了以下腳本
#! /usr/bin/python
import glob
path = raw_input('In which dir do you want to look for the files?')
path += '/*.txt'
files=glob.glob(path)
for seq in files:
f=open(seq)
total = 0
for line in f:
if 'NAR' in line:
print("bum")
f.close()
因此,如果我有一個像這樣的文件:
NAR 56 rob
NAR 0-0 co
FOR 56 gs
FRI 69 ds
NIR 87 sdh
我希望我的代碼可以打印
bum bum
然后我在這里閱讀后嘗試了以下內容
#! /usr/bin/python
import glob
path = raw_input('In which dir do you want to look for the files?')
files=glob.glob(path)
for seq in files:
with open(seq) as input_file:
for line in input_file:
if 'NAR' in line:
print("bum")
input_file.close()
但兩者都不起作用。 我在這里做錯了什么?
您的files
列表僅包含目錄,而不會查找寫入的文件。 例如,如果您嘗試匹配txt
文件,則需要說
path += '\*.txt'
因此, glob
查找txt
文件。 代替
'C:\folder\folder'
搜索將是
'C:\folder\folder\*.txt'
如果path
確實是現有目錄的路徑,沒有通配符,則glob.glob
將返回僅包含該目錄的單項列表。
您可能希望在glob.glob
調用之前添加類似
if not path.endswith('*'):
path = os.path.join(path, '*')
或更一般而言,您的情況可能是:
if '*' not in path:
但是,如果您對通配符感到滿意,那么在丟失通配符的地方添加它並不明顯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.