Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.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_Search_Text_Full Text Search - Fatal编程技术网

如何修改脚本以允许Python递归搜索我的文件夹结构?

如何修改脚本以允许Python递归搜索我的文件夹结构?,python,search,text,full-text-search,Python,Search,Text,Full Text Search,喂,蟒蛇们 我有一个脚本,它在单个目录中包含的所有文件中搜索“string”关键字。如果它在任何文件中找到“string”关键字,它将在IDLE命令屏幕上打印此文件的名称。它似乎工作得很好。输入由程序使用用户提示收集。通常,我在一大系列文本文件中搜索单个单词 然而,现在我想从两个方面来构建它 1) 我想修改代码,使其也可以搜索指定目录子文件夹中包含的所有文件。 2) 我还想指定搜索仅限于某种类型的文件扩展名,如.txt 有人能就这两个增强功能中的任何一个提供一些指导吗 我正在使用Python3,

喂,蟒蛇们

我有一个脚本,它在单个目录中包含的所有文件中搜索“string”关键字。如果它在任何文件中找到“string”关键字,它将在IDLE命令屏幕上打印此文件的名称。它似乎工作得很好。输入由程序使用用户提示收集。通常,我在一大系列文本文件中搜索单个单词

然而,现在我想从两个方面来构建它 1) 我想修改代码,使其也可以搜索指定目录子文件夹中包含的所有文件。 2) 我还想指定搜索仅限于某种类型的文件扩展名,如.txt

有人能就这两个增强功能中的任何一个提供一些指导吗

我正在使用Python3,对Python非常陌生(2周前刚刚开始使用它,试图通过我的雇主文件夹结构自动执行一些无聊的搜索)

非常感谢任何能提供帮助的人。 干杯 弗拉兹


查看
os.walk
欢迎来到StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。在这里申请。StackOverflow不是设计、编码、研究或教程服务。研究先行;然后邮寄。这两个问题在堆栈溢出和其他地方的许多地方都得到了处理。感谢各位的评论,我将在脚本中加入os.walk。
# This script will search through all files within a single directory for a single key word
# If the script finds the word within any of the files it will print the name of this file to the command line

import os

print ('When answering questions, do not add a space and use forward slash separators on file paths')
print ('')

# Variables to be defined by user input
user_input = input('Paste the directory you want to search?')
directory = os.listdir(user_input)
searchstring = input('What word are you trying to find within these files?')


for fname in directory:
    if os.path.isfile(user_input + os.sep + fname):
        # Full path
        f = open(user_input + os.sep + fname, 'r')

        if searchstring in f.read():
            print('found string in file "%s"' % fname)
        f.close()enter code here