Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在目录中搜索字符串_Python_String_Directory_Subdirectory - Fatal编程技术网

Python 在目录中搜索字符串

Python 在目录中搜索字符串,python,string,directory,subdirectory,Python,String,Directory,Subdirectory,嗨,我写了这段代码来搜索文件列表中的关键字 import glob import os print "enter directory path" path=raw_input() print "Enter keyword" key=raw_input() os.chdir(path) for files in glob.glob("*.*"): with open(file) as f: contents=f.read() if key in contents:

嗨,我写了这段代码来搜索文件列表中的关键字

import glob
import os
print "enter directory path"
path=raw_input()
print "Enter keyword"
key=raw_input()
os.chdir(path)
for files in glob.glob("*.*"):
    with open(file) as f:
         contents=f.read()
    if key in contents:
          print file
我对Python比较陌生。有人能帮我修改同样的代码,以便在子目录中搜索吗???

使用:


我试过这个,但它显示了一个类似这样的回溯错误(上次调用):文件“s.py”,第10行,打开(文件)为fdf:IOError:[Errno 2]没有这样的文件或目录:“accounts.cfg”如果你使用linux,那么使用
子进程
模块调用
grep
要快得多。我不知道如何使用它。我只是一个初学者
for root, dirs, files in os.walk(your_dir_path):
    for file in files:
        file = os.path.join(root, file)    
        with open(file) as f:
             ...