Python搜索字符串并打印它所在的文件 [英] Python Searching for String and printing the file it is in

查看:250
本文介绍了Python搜索字符串并打印它所在的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在做的是让用户把字符串搜索。程序将搜索定义目录中的多个.txt文件,然后打印结果,或使用默认文本编辑器打开.txt文件。

有人可以请我指出这个搜索功能的正确方向吗?

p>

编辑:
这是我到目前为止所做的。我不能使用grep作为这个程序将运行在Windows以及OSX。我还没有在Windows上测试,但是在OSX上,我的结果是拒绝访问的。

  import os 
import subprocess

text = str(raw_input(输入要搜索的文本:))

thedir ='./f'
用于os中的文件。 listdir(thedir):
文件= os.path.join(thedir,文件)
用于打开文档中的行:
如果文本在行:
subpocess.call document,shell = True)


解决方案

你可以用 os.walk 遍历指定目录结构中的所有文件,搜索字符串,使用 subprocess 模块在需要的编辑器中打开文件...


I am working on a small program for work, and I have looked everywhere for help on this!

What I'm trying to do is to allow the user to put in string to search. The program will search multiple .txt files in a defined directory for the string and then either print the result, or open the .txt file using the default text editor.

Can someone please point me in the right direction for this search feature?

Thanks in advance!

Edit: This is what I have so far. I cant use grep as this program wil be running on Windows as well as OSX. I have yet to test on Windows, but on OSX my results are access denied.

import os
    import subprocess

    text = str(raw_input("Enter the text you want to search for: "))

    thedir = './f'
    for file in os.listdir(thedir):
        document = os.path.join(thedir, file)
        for line in open(document):
            if text in line:
                subpocess.call(document, shell=True)

解决方案

below are hints to your answer :)

You can use os.walk to traverse all the files in the specified directory structure, search the string in the file, use subprocess module to open the file in the required editor...

这篇关于Python搜索字符串并打印它所在的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆