if条件在python中不起作用的迭代

时间:2015-01-22 15:00:34

标签: python for-loop

我写了以下脚本

#! /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

然后我在阅读here

后尝试了以下内容
#! /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()

但两者都不起作用。我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

您的files列表只包含目录,不会查找写入的文件。如果您要匹配,例如,您需要说明{/ 1}}文件

txt

因此path += '\*.txt' 会查找glob个文件。而不是

txt

然后搜索

'C:\folder\folder'

答案 1 :(得分:0)

如果path确实是现有目录的路径,没有通配符,则glob.glob将返回仅具有该目录的单项列表。

您可能希望在glob.glob来电之前添加类似

的内容
if not path.endswith('*'):
    path = os.path.join(path, '*')

或更一般地说,您的情况可能是:

if '*' not in path:

虽然如果您对任何地方的通配符感到满意,但如果它丢失了,您将添加它的位置并不明显。