简体   繁体   English

在Python中递归读取文件夹

[英]Reading folders recursively in Python

The purpose of this program is to recursively look through all the files and directories in a root directory to find any matches of a key phrase (named file in main method). 该程序的目的是递归地浏览根目录中的所有文件和目录,以查找关键字(在main方法中命名的文件)的任何匹配项。 My main issue is that I cannot figure out how to get into the subdirectories and make sure I loop through all of the files and directories in it, and then continue doing so until I've went through all directories in the tree that started from the root directory. 我的主要问题是我无法弄清楚如何进入子目录并确保遍历其中的所有文件和目录,然后继续这样做,直到遍历从树开始的树中的所有目录为止。根目录。

Here is my current code. 这是我当前的代码。

import os
import sys

def search_dir(path):
    for root, dirs, files in os.walk(os.path.abspath(path)):
        for f in files:
            if file in f:
                print("File : {}".format(os.path.join(root, f)))
        for d in dirs:
            if file in d:
                print("Dir  : {}".format(os.path.join(root, d)))

def main(file, path):
    print("Starting search for '{}'\n".format(file))
    search_dir(path)
    print("\nDone Searching")


if __name__ == "__main__":
    if len(sys.argv)!=3:
        print("Usage: python find_file.py [path] [file]")
    else:
        path, file = sys.argv[1], sys.argv[2]
        main(file, path)

I've tried changing directories using os.chdir(new_path) but I end up running into problems as I get lost on when to change directories back etc. I feel as though there is a way to recursively use the search_dir function, but after much thought I cannot execute it correctly. 我曾尝试使用os.chdir(new_path)来更改目录,但是由于无法及时更改目录等,我最终遇到了麻烦。我觉得好像有一种递归使用search_dir函数的方法,但是经过很多次以为我不能正确执行它。

This should do it: 应该这样做:

import os

def search_dir(root, search):
    for root, _dirnames, fnames in os.walk(root):
        for fname in fnames:
            fpath = os.path.join(root, fname)
            with open(fpath) as infile:
                if any(search in line for line in infile):
                    print("Search term found in", fpath)


if _name__ == "__main__":
    if len(sys.argv)!=3:
        print("Usage: python find_file.py [path] [searchTerm]")
    else:
        path, search = sys.argv[1], sys.argv[2]
        main(file, search)

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

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