python 查找文件内容
输入查找的文件夹路径,要查找的内容关键字(可以指定多个),要查找的文件类型(可以是多个),搜索出符合条件的文件,并记录所有符合条件的行号及行内容。
写的感觉有点冗余,但好歹还能使用^-^,主要是方便手头工作。
# 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 查找文件内容的更多相关文章
- Linux里如何查找文件内容
Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符串" 文件名例子:在当前目录里第一级文件夹中寻找包含指定字符串的.in文件g ...
- Linux里如何查找文件内容 (转)
Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符串" 文件名例子:在当前目录里第一级文件夹中寻找包含指定字符串的.in文件g ...
- 【转】Linux里如何查找文件内容
原文网址:http://blog.chinaunix.net/uid-25266990-id-199887.html Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ g ...
- Python 输出文件内容到网络端口
Python 输出文件内容到网络端口 $ cat mySocketTest.py import sys import time import socket if __name__ == "_ ...
- 在Linux下查找文件内容包含某个特定字符串的文件
如何在Linux下查找文件内容包含某个特定字符串的文件? 我的目录下面有test1和test2两个文件夹,里面都含有很多文件,其中test2里面还包含一个test文件夹 我想请问的是,如何通过查找关键 ...
- python 修改文件内容
python 修改文件内容 一.修改原文件方式 1 def alter(file,old_str,new_str): 2 """ 3 替换文件中的字符串 4 :param ...
- [转] Linux 查找文件内容
Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符串" 文件名例子:在当前目录里第一级文件夹中寻找包含指定字符串的.in文件g ...
- linux grep 查找文件内容
自试: wang@wang:~$ grep -i "*args*" ~/IGV01-SW/src/bzrobot_diagnostics/bzrobot_lightbelt_man ...
- Linux查找文件内容小技巧
目录 grep ag linux系统查找文件内容最常见的命令有grep和ag grep grep是比较常见的查找命令 # 在当前目录的py文件里查找所有相关内容 grep -a "broad ...
随机推荐
- Android编译系统环境初始化过程分析
Android源代码在编译之前,要先对编译环境进行初始化,其中最主要就是指定编译的类型和目标设备的型号.Android的编译类型主要有eng.userdebug和user三种,而支持的目标设备型号则是 ...
- java实现windows下amr转换为mp3(可实现微信语音和qq语音转换)
最近做一个项目需要将微信的语音文件放在页面进行播放,查了好多资料发现,web页面直接播放并没有一个好的解决方案,于是就想到了先将amr文件转换成易于在页面播放的mp3文件,然后在进行播放,现在将amr ...
- Django的AutoField字段
[Django是一个机智的框架] 默认情况下Djang会为ORM中定义的每一张表加上一个自增ID列,并且用这个列来做主键:出于一个MySQL-DBA的工作经历我觉得 Djanog还真是机智:这样么说主 ...
- CentOS 7 设置iptables防火墙开放proftpd端口
由于ftp的被动模式是这样的,客户端跟服务器端的21号端口交互信令,服务器端开启21号端口能够使客户端登录以及查看目录.但是ftp被动模式用于传输数据的端口却不是21,而是大于1024的随机或配置文件 ...
- activiti设置流程变量
public static void mian(String args[]){ ProcessEngine processEngine = ProcessEngine.getDefaultProce ...
- Oozie-自定义实现WorkFlow中shell action
拷贝默认的shell目录来进行修改 $ cp -r ./examples/apps/shell/ my-apps/ 定义job.properties nameNode=hdfs://bigdata-0 ...
- html5自定义数字键盘
原理:使用div模拟输入框,避免手机原生键盘弹出,键盘使用div模拟,点击事件使用js控制,光标闪烁使用css模拟,具体代码如下: <!doctype html> <html lan ...
- LL&LR parser
https://stackoverflow.com/questions/5975741/what-is-the-difference-between-ll-and-lr-parsing https:/ ...
- performance Counter
Logman https://technet.microsoft.com/en-us/library/bb490956.aspx http://blogs.technet.com/b/askperf/ ...
- 利用es-checker检测当前node对ES6的支持情况
ode.js发展非常快,对es6特性的支持也越来越良心,但node.js版本很多,各版本对es6的支持度都不一样,为了能清晰的了解各版本对es6特性的支持,需要有一个工具能提供比较清晰的支持说明,甚至 ...