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?
-
Are you passing the FULL directory path to the glob() method ? and also print the files returned by that function for debugging purposesZdaR– ZdaR2015年01月22日 15:03:18 +00:00Commented Jan 22, 2015 at 15:03
2 Answers 2
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'
1 Comment
print(files) in the script I get []. It seems that it does not find any file, isn't it?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.