繁体   English   中英

扫描目录,在文件中查找字符串并打印结果

[英]Scan directories, find string within files and print results

标题可能不会给任何人以公义,所以让我正确地说。 我正在尝试编写一个程序,该程序将扫描我的驱动器E:\\以获取单词列表,例如waterfireair 在我的E:\\驱动器中,很明显,我的文件夹中有文件夹,文件夹中有文件,依此类推。

我想调用函数search (path, text) ,该函数search (path, text)用文本形式输入列表['water', 'fire', 'air'] 看起来像这样: search('E:\\\\', ['water', 'fire', 'air'])

我希望能够扫描目录,并使用它扫描的每个“行”打印“ Scanning: E:\\\\... 我有这个。 我也想在发现水,火和/或空气时输出In (directory name) found water, fire In (directory name) found air ,等等。我拥有大部分内容。 我无法弄清楚如何显示多个单词(如果适用)。

我正在寻找的输出将是这样的,例如:

Scanning: E:\\ Scanning: E:\\Python Fun! Scanning: E:\\Python Fun!\\1st Week Scanning: E:\\Python Fun!\\2nd Week Scanning: E:\\Python Fun!\\3rd Week In E:\\Python Fun!\\3rd Week\\elements.txt found 'fire', 'water' Scanning: E:\\Python Fun!\\4th Week Scanning: E:\\Python Fun!\\5th Week In E:\\Python Fun!\\5th Week\\elements.txt found 'air Scanning... Scanning: E:\\ Scanning: E:\\Python Fun! Scanning: E:\\Python Fun!\\1st Week Scanning: E:\\Python Fun!\\2nd Week Scanning: E:\\Python Fun!\\3rd Week In E:\\Python Fun!\\3rd Week\\elements.txt found 'fire', 'water' Scanning: E:\\Python Fun!\\4th Week Scanning: E:\\Python Fun!\\5th Week In E:\\Python Fun!\\5th Week\\elements.txt found 'air Scanning...等等上

这是我的代码:

import os
def search(path, text):

    for text in texts:
        if os.path.isfile(path): #base case
            if text in path:
                print(path)
            return

    if not os.path.exists(path):
        return

    for item in os.listdir(path):
        itempath = os.path.join(path, item)

        if os.path.isfile(itempath):
            if text in item:
                print('In {} found {}'.format(itempath, word))

        elif os.path.isdir(itempath):

            search(itempath, text)
            print('Scanning:', path)
            #open(itempath).read() #tested this but got an error. See below.
        else: #unknown object type
            pass

search('E:\\',['water','fire', 'air'])

我得到的Traceback错误是AttributeError: 'str' object has no attribute 'read' 所以我把它注释掉了。

通过此代码,我得到的基本上是列表中任何字母的最后一个字母的结果,在这种情况下, r代表正在搜索的内容。 我在想那是由于一个额外的循环? 但是不确定。

我知道我需要在某个地方添加一个open filename ,但是再次,我对如何实现它感到困惑。 我刚刚开始学习OS模块,因此大量的混乱开始发挥作用。 我感到难过。

要递归地迭代驱动器,请考虑使用glob代替:

import glob

for filename in glob.iglob('E:/**/**', recursive=True):
    print("Scanning", filename);
    with open(filname, 'r', encoding='utf-8') as file: content = file.read()
    for text in texts:
        if text in content:
            print("Found:", text, " - ", filename);

为了扫描文件的内容,您还需要open()它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM