- 帖子
- 9
- 精华
- 0
- 积分
- 45
- 阅读权限
- 10
- 注册时间
- 2017-3-6
- 最后登录
- 2017-9-4
|
模仿上一个题目的一个解答编写的。让用户提供文件夹,文件类型和搜索文本。
#!/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])
|
|