设为首页收藏本站

Crossin的编程教室

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

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

[复制链接]

1

主题

0

好友

45

积分

新手上路

Rank: 1

楼主
发表于 2017-3-7 15:43:42 |显示全部楼层
模仿上一个题目的一个解答编写的。让用户提供文件夹,文件类型和搜索文本。

#!/usr/bin/python
#This file is used to search files in path A. The names of the files contains B, and the content of the files contain C
#the input should like this:python search.py A B C

import os
import re
import sys

def searchmethod(path,filetype,text):
  all=[]
  for dirpath, dirnames, filenames in os.walk(path):
    for filename in filenames:
      f=file(os.path.join(dirpath,filename))
      content=f.read()
      f.close()
      #print content
      if os.path.splitext(filename)[1]==filetype and re.findall(text, content): # to match file type and file content
        all.append(os.path.join(dirpath,filename))
  print all

if __name__=='__main__':
  if len(sys.argv) !=4:
    print 'Please input like this:./9.py your_dir file_type your_match_string'
  elif os.path.exists(sys.argv[1]):
    searchmethod(sys.argv[1],sys.argv[2],sys.argv[3])
回复

使用道具 举报

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

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

GMT+8, 2024-5-4 14:41 , Processed in 0.015475 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部