设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 32231|回复: 0
打印 上一主题 下一主题

【每日一坑 6】 查找文件内容

[复制链接]

0

主题

0

好友

389

积分

中级会员

Rank: 3Rank: 3

楼主
发表于 2013-12-26 22:32:29 |显示全部楼层

回帖奖励 +5

本帖最后由 fl0w 于 2013-12-26 22:35 编辑

findThemAll.py
  1. #! /usr/bin/env python
  2. # coding:utf-8

  3. import sys
  4. import os
  5. import fnmatch
  6. import re

  7. def filterFilename(path, text):
  8.     fileList = []
  9.     for dirpath, dirnames, filenames in os.walk(path):
  10.         for filename in filenames:
  11.             if fnmatch.fnmatch(filename, text):
  12.                 fileList.append(os.path.join(dirpath, filename))
  13.     return fileList

  14. if __name__ == "__main__":
  15.     if len(sys.argv) < 3:
  16.         print 'Please input like this:./findThemAll.py your_dir your_match_string'
  17.     elif os.path.exists(sys.argv[1]):
  18.         fileList = filterFilename(sys.argv[1],'*.txt')
  19.         themAll = []
  20.         for file in fileList:
  21.             with open(file) as f:
  22.                 content = f.read()
  23.                 if len(re.findall(sys.argv[2], content)) > 0:
  24.                     themAll.append(file)
  25.         print 'The files under %s contain "%s" are:' % (sys.argv[1], sys.argv[2])
  26.         print themAll
  27.     else:
  28.         print 'Are you sure the path is exist?'
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-3 10:01 , Processed in 0.024116 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部