当我尝试打开并读取目录中文件中的对象时出现回溯错误。我究竟做错了什么?

I get a traceback error when I try to open and read through the objects in a file in a directory. What am I doing wrong?

我的程序的重点是通过一个目录(由用户给定)搜索打开目录中的文件,打开文件中的东西并在文件中的文档中查找字符串。我使用一个名为 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

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

的文件

尝试摆脱第二个循环。另外,不要忘记在打开时指定目录名称。另外,考虑更改命名方案,以便可以消除 file 对象和 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

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)