本站消息

站长简介/公众号


站长简介:高级软件工程师,曾在阿里云,每日优鲜从事全栈开发工作,利用周末时间开发出本站,欢迎关注我的微信公众号:程序员总部,程序员的家,探索程序员的人生之路!分享IT最新技术,关注行业最新动向,让你永不落伍。了解同行们的工资,生活工作中的酸甜苦辣,谋求程序员的最终出路!

  价值13000svip视频教程,python大神匠心打造,零基础python开发工程师视频教程全套,基础+进阶+项目实战,包含课件和源码

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

How can I modify my script to allow Python to search recursively thought my folder structure?

发布于2021-10-15 00:14     阅读(369)     评论(0)     点赞(17)     收藏(2)



Hello fellow Pythonistas,

I have a script which searches through all files contained within a single directory for a 'string' keyword. If it finds the 'string' keyword within any of the files, it will print the name of this file to the IDLE command screen. It seems to work quite well. The inputs are gathered by the program using user prompts.Typically I am searching for a single word within a large series of text files.

HOWEVER - Now I want to build on this in two ways 1) I want to modify the code to that it can also search through all the files contained within sub-folders within the specified directory. 2) I would also like to specify that the searches are limited to a certain type of file extension such as .txt.

Can anyone provide some guidance on either of these two enhancements ???

I am using Python 3 and am VERY new to Python (Just started playing with it 2 weeks ago in an attempt to automate some boring searches through my employers folder structures)

Much appreciated to anyone who can provide some help. Cheers, Fraz

# 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

解决方案


暂无回答







所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/1059591/a06239d9afe2c8e8a3c5/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

17 0
收藏该文
已收藏

评论内容:(最多支持255个字符)