0

我的程序的重点是搜索目录(由用户提供)打开目录中的文件,打开文件中的内容并在文件中的文档中查找字符串。我使用一个名为 easygui 的 GUI 来询问用户的输入。当我运行程序时,出现两个错误:

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'

我也 100% 确定文件或目录不是'm'

这是我的代码:

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
4

2 回答 2

2

看起来你有一个太多的for循环。for items in file:遍历文件名中的每个字母。例如,如果您有一个名为“main.txt”的文件,它将尝试打开一个名为“m”的文件,然后打开一个名为“a”的文件......

尝试摆脱第二个循环。另外,打开时不要忘记指定目录名称。此外,请考虑更改命名方案,以便消除文件对象和文件名字符串之间的歧义。

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
于 2015-07-28T15:41:04.783 回答
1

os.listdir(folder) 为您提供文件夹中包含文件名的字符串列表。看控制台:

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

每个项目都是一个字符串,因此当您对它们进行迭代时,您实际上是在将它们的名称作为字符串进行迭代:

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

如果您希望遍历特定目录中的文件,则应在其上再次创建 listdir:

for items in os.listdir(file):  # <!-- not file, but os.listdir(file)
    open(items)
于 2015-07-28T15:48:46.173 回答