efrem
efrem

Reputation: 455

Iteration with if condition not working in python

I wrote the following script

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

So if I have a file like this:

NAR 56 rob
NAR 0-0 co
FOR 56 gs
FRI 69 ds
NIR 87 sdh

I would expect my code to print

bum bum

Then I tried the following after reading 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()

but both do not work. What I am doing wrong here?

Upvotes: 0

Views: 56

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117856

Your list of files just contains the directory, and will not look for files as written. If you are trying to match, for example, txt files you would need to say

path += '\*.txt'

So glob looks for txt files. Instead of

'C:\folder\folder'

The search would then be

'C:\folder\folder\*.txt'

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881477

If path is indeed a path of an existing directory, without wildcards, then glob.glob will return a single-item list with just that directory.

You may want, before the glob.glob call, to add something like

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

or more generally, your condition could be:

if '*' not in path:

though if you're happy with a wildcard anywhere it's not obvious where you would add it if it was missing.

Upvotes: 0

Related Questions