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

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

# 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. Web用户控件开发--星型评分控件

    本文中分享一个实现简单,使用方便的星型评分控件. 一:贴几张测试图片先: 二.星型评分控件的实现: RatingBar.ascx: <%@ Control Language="C#&q ...

  2. Qt Creator中如何添加C++0x支持

    最近在学习多线程编程,本人平时习惯使用Qt Creator写程序,只是作为C++编辑器,很少使用Qt library中的类. Multi Threading作为C++11标准已经纳入C++标准库了,可 ...

  3. nginx增加ssl支持 - 编译时参数详情列表

    ./configure \ --with-http_ssl_module \ make && make install     nginx编译参数说明如下:   --prefix=&l ...

  4. MySql(十七):MySql架构设计——高可用设计之思路及方案

    前言: 数据库系统是一个应用系统的核心部分,要想系统整体可用性得到保证,数据库系统就不能出现任何问题.对于一个企业级的系统来说,数据库系统的可用性尤为重要.数据库系统一旦出现问题无法提供服务,所有系统 ...

  5. oozie 常用命令

    1.验证wokflow.xmloozie validate /appcom/apps/hduser0401/mbl_webtrends/workflow.xml 2.提交作业,作业进入PREP状态 o ...

  6. Oozie介绍

    1. Hadoop常见调度框架: (1)Linux Crontab:Linux自带的任务调度计划,在任务比较少的情况下,可以使用这种方式,直接执行脚本,例如添加一个执行计划: 0 12 * hive ...

  7. 【Android开发】构建Android源码编译环境

    原文:http://android.eoe.cn/topic/android_sdk 构建Android源码编译环境 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  8. iOS提交iTunes审核时出现Invalid Binary错误

    xcode5编译一个xcode4时写的代码,提交iTunes审核时出错. 1.iOS提交审核时出现Invalid Binary错误 2.收到邮件: iPhone 5 Optimization Requ ...

  9. sql左右连接测试

    with a as (select 1 as id, 'name1'as nameunionselect 2 as id, 'name2'as nameunionselect 3 as id, 'na ...

  10. 每日英语:Political Gridlock, Beijing Style

    To admirers outside the country, China's political system stands far above the dysfunctional democra ...