I’m trying to find a string in files contained within a directory. I have a string like banana
that I know that exists in a few of the files.
JavaScript
x
14
14
1
import os
2
import sys
3
4
user_input = input("What is the name of you directory?")
5
directory = os.listdir(user_input)
6
searchString = input("What word are you trying to find?")
7
8
for fname in directory: # change directory as needed
9
if searchString in fname:
10
f = open(fname,'r')
11
print('found string in file %s') %fname
12
else:
13
print('string not found')
14
When the program runs, it just outputs string not found
for every file. There are three files that contain the word banana
, so the program isn’t working as it should. Why isn’t it finding the string in the files?
Advertisement
Answer
You are trying to search for string
in filename
, use open(filename, 'r').read()
:
JavaScript
1
18
18
1
import os
2
3
user_input = input('What is the name of your directory')
4
directory = os.listdir(user_input)
5
6
searchstring = input('What word are you trying to find?')
7
8
for fname in directory:
9
if os.path.isfile(user_input + os.sep + fname):
10
# Full path
11
f = open(user_input + os.sep + fname, 'r')
12
13
if searchstring in f.read():
14
print('found string in file %s' % fname)
15
else:
16
print('string not found')
17
f.close()
18
We use user_input + os.sep + fname
to get full path.
os.listdir
gives files and directories names, so we use os.path.isfile
to check for files.