0

私のプログラムのポイントは、(ユーザーが指定した)ディレクトリを検索してディレクトリ内のファイルを開き、ファイル内のものを開いて、ファイル内のドキュメント内の文字列を探すことです。easygui という GUI を使用して、ユーザーに入力を求めます。プログラムを実行すると、次の 2 つのエラーが発生します。

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」という名前のファイルを開こうとします...

2 番目のループを取り除きます。また、開くときにディレクトリ名を指定することを忘れないでください。また、ファイルオブジェクトとファイル名文字列を明確に区別できるように、命名規則を変更することも検討してください。

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 に答える