输入查找的文件夹路径,要查找的内容关键字(可以指定多个),要查找的文件类型(可以是多个),搜索出符合条件的文件,并记录所有符合条件的行号及行内容。

写的感觉有点冗余,但好歹还能使用^-^,主要是方便手头工作。

# coding:utf8
import os
from os.path import * # enter the search dir
print r"""Search file tool(Ver1.0)
dirpath /k keywords [/e fileextension] [/o resultfilepath]
/k keyword you want to search
/e file extension(.txt .java .cs etc...)
/o the path of the result file you want to save
example:
e:\temp\py /k 'kw1' /e '.txt'
e:\temp\py /k "kw1" "kw2" /e ".txt" ".cs" /o e:\temp\py\result.txt
""" # Get user command.
input = raw_input("> ")
if input.find("/k") < 0:
print "/k option must be input"
exit(1) # Get the dir
root_dir = input.split("/k")[0].strip()
if not isdir(root_dir):
print "First parameter must be a valid dir!"
exit(1) # Get the keywords and file extension
option = input.split("/k")[1].strip()
if option.find("/e") < 0:
key_words = [s.strip("\'\"") for s in option.split()]
else:
key_words = [s.strip("\'\"") for s in option.split("/e")[0].strip().split()]
if option.find("/o") < 0:
file_exts = [s.strip("\'\"") for s in option.split("/e")[1].strip().split()]
else:
file_exts = [s.strip("\'\"") for s in option.split("/e")[1].strip().split("/o")[0].strip().split()] search_filter = "Search dir:%s\n" % root_dir
search_filter = search_filter + ("Search key words:%s\n" % " ".join(key_words))
if file_exts:
search_filter = search_filter + ("Search file type:%s\n" % " ".join(file_exts))
print search_filter # Search file by the keyword
result_files = {}
for (dir_name, subdirs, files) in os.walk(root_dir):
for file in files:
filepath = os.path.join(dir_name, file)
ext = os.path.splitext(filepath)[1]
if file_exts and (ext not in file_exts):
continue file = open(filepath)
# Compare every lines of the file by the keywords
for index, line in enumerate(file.readlines()):
for keyword in key_words:
if line.find(keyword) > 0:
# Save matched line and line number
match_line = "line:%d %s" % (index, line)
if filepath not in result_files.keys():
result_files[filepath] = []
result_files[filepath].append(match_line)
break
file.close()
print "Search finish!" # Output the search result
if option.find("/o") >= 0:
# Write result to file
save_file_path = option.split("/o")[len(option.split("/o")) - 1].strip()
save_file = open(save_file_path, "w")
save_file.write(search_filter)
summary = "find:%d files" % len(result_files.keys())
save_file.write("%s\n" % summary)
for key, value in result_files.items():
save_file.write("%s\n" % key)
for line in value:
#print "type:", type(line)
save_file.write("--%s" % line)
save_file.close()
else:
# Show result in command window
summary = "find:%d files" % len(result_files.keys())
print summary
for key, value in result_files.items():
print "%s" % key
for line in value:
print "--%s" % line 直接运行,就可以提示你如何操作,第一个实用的python程序,记录一下。

python 查找文件内容的更多相关文章

  1. Linux里如何查找文件内容

    Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符串" 文件名例子:在当前目录里第一级文件夹中寻找包含指定字符串的.in文件g ...

  2. Linux里如何查找文件内容 (转)

    Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符串" 文件名例子:在当前目录里第一级文件夹中寻找包含指定字符串的.in文件g ...

  3. 【转】Linux里如何查找文件内容

    原文网址:http://blog.chinaunix.net/uid-25266990-id-199887.html Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ g ...

  4. Python 输出文件内容到网络端口

    Python 输出文件内容到网络端口 $ cat mySocketTest.py import sys import time import socket if __name__ == "_ ...

  5. 在Linux下查找文件内容包含某个特定字符串的文件

    如何在Linux下查找文件内容包含某个特定字符串的文件? 我的目录下面有test1和test2两个文件夹,里面都含有很多文件,其中test2里面还包含一个test文件夹 我想请问的是,如何通过查找关键 ...

  6. python 修改文件内容

    python 修改文件内容 一.修改原文件方式 1 def alter(file,old_str,new_str): 2 """ 3 替换文件中的字符串 4 :param ...

  7. [转] Linux 查找文件内容

    Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符串" 文件名例子:在当前目录里第一级文件夹中寻找包含指定字符串的.in文件g ...

  8. linux grep 查找文件内容

    自试: wang@wang:~$ grep -i "*args*" ~/IGV01-SW/src/bzrobot_diagnostics/bzrobot_lightbelt_man ...

  9. Linux查找文件内容小技巧

    目录 grep ag linux系统查找文件内容最常见的命令有grep和ag grep grep是比较常见的查找命令 # 在当前目录的py文件里查找所有相关内容 grep -a "broad ...

随机推荐

  1. STM8在IAR中Option Byte配置

    转http://www.stmcu.org/module/forum/thread-607140-1-1.html 近期帮客户调试STM8的程序使用到OptionByte配置,在网上查询几乎都是介绍如 ...

  2. jQueryWEUI自定义对话框-带有textarea

    jQueryWEUI  示例下载 在jQueryWEUI中提供了很多类型的对话框, 可以去访问看一下. 今天记录的则是,自己定义的一个带有文本域的对话框,这样,可以不通过调转页面,实现一些信息的提交. ...

  3. django-salmonella的使用

    一.django-salmonella介绍 它是一个Django管理员raw_id_fields小部件替换,用于处理更改时显示对象的字符串值,并且可以通过模板覆盖. 二.安装 1.下载 $ pip i ...

  4. JDK1.5新特性,基础类库篇,集合框架(Collections)

    集合框架在JDK1.5中增强特性如下: 一. 新语言特性的增强 泛型(Generics)- 增加了集合框架在编译时段的元素类型检查,节省了遍历元素时类型转换代码量. For-Loop循环(Enhanc ...

  5. [na]TCP的三次握手四次挥手/SYN泛洪

    1.TCP报文格式 上图中有几个字段需要重点介绍下: (1)序号:Seq序号,占32位,用来标识从TCP源端向目的端发送的字节流,发起方发送数据时对此进行标记. (2)确认序号:Ack序号,占32位, ...

  6. lua -- 点击关闭窗口中的子界面

    function UIBagController:initBoxView( ) self.panelBox = tolua.cast(UIHelper:seekWidgetByName(self.ow ...

  7. KVM虚拟机安装报错 KVM is not available

    在linux系统上使用kvm安装系统时,如果你的cpu不支持虚拟化技术那么可能会报以下错误: Warning:KVM is not available. This may mean the KVM p ...

  8. [Windows Azure] Guidelines for Connecting to Windows Azure SQL Database

    Guidelines for Connecting to Windows Azure SQL Database 6 out of 12 rated this helpful - Rate this t ...

  9. java多线程14 :wait()和notify()/notifyAll()

    轮询 线程本身是操作系统中独立的个体,但是线程与线程之间不是独立的个体,因为它们彼此之间要相互通信和协作. 想像一个场景,A线程做int型变量i的累加操作,B线程等待i到了10000就打印出i,怎么处 ...

  10. 使用线性回归识别sklearn中的手写数字digit

    从昨天晚上,到今天上午12点半左右吧,一直在调这个代码.最开始训练的时候,老是说loss:nan 查了资料,因为是如果损失函数使用交叉熵,如果预测值为0或负数,求log的时候会出错.需要对预测结果进行 ...