0

The point of my program is to search through a directory (given by the user) open the files in the directory, open the things in the files and look for a string inside the documents in the files. I use a GUI called easygui to ask the user fir input. When I run the program I get a two errors:

Traceback (most recent call last):

  File "C:\Users\arya\Documents\python\findstrindir", line 11, in <module>
    open(items)
IOError: [Errno 2] No such file or directory: 'm'

I am also 100% percent sure that the file or directory is not 'm'

This is my code:

import os, easygui, sys

path = easygui.enterbox(msg='Enter Directory')
strSearch = easygui.enterbox(msg = 'Enter String to search for')
dirs = os.listdir(path)
fCount = 0
strCount = 0
for file in dirs:
    fCount += 1
    for items in file:
        open(items)
        trt = items.read()
        for strSearch in trt:
            strCount +=1

print "files found:", fCount
clemtoy
  • 1,681
  • 2
  • 18
  • 30
Arya Shah
  • 3
  • 1

2 Answers2

2

Looks like you have one too many for loops. for items in file: iterates through every letter in the file name. For example, if you have a file named "main.txt", it will attempt to open a file named "m", then a file named "a"...

Try getting rid of the second loop. Also, don't forget to specify the directory name when opening. Also, consider changing your naming scheme so you can disambiguate between file objects and file name strings.

import os, easygui, sys

path = easygui.enterbox(msg='Enter Directory')
strSearch = easygui.enterbox(msg = 'Enter String to search for')
filenames = os.listdir(path)
fCount = 0
strCount = 0
for filename in filenames:
    fCount += 1
    f = open(os.path.join(path, filename))
    trt = f.read()
    for strSearch in trt:
        strCount +=1

print "files found:", fCount
Kevin
  • 74,910
  • 12
  • 133
  • 166
1

os.listdir(folder) gives you a list of string with filenames in the folder. Look at the console:

>>> import os
>>> os.listdir('.')
['file1.exe', 'file2.txt', ...]

Each item is a string, so when you are iterating over them, you are iterating over their names as strings indeed:

>>> for m in 'file1':
...     print(m)
...
f
i
l
e

If you wish to iterate over files in a specific directory you should make listdir again on it:

for items in os.listdir(file):  # <!-- not file, but os.listdir(file)
    open(items)
Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59