0

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?

1
  • Are you passing the FULL directory path to the glob() method ? and also print the files returned by that function for debugging purposes Commented Jan 22, 2015 at 15:03

2 Answers 2

1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Good point. I followed your suggestion and also @Anmol_uppal 's one. It still does not print anything, but if I include print(files) in the script I get []. It seems that it does not find any file, isn't it?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.