Python查找文件内容

来源:互联网 发布:大数据薪资待遇 编辑:程序博客网 时间:2024/06/05 18:42

简单的文件内容搜索脚本

根据关键字遍历指定文件路径下的文件,可以指定需要搜索文件的类型

# coding=utf8import osimport os.pathrootdir = r"/Users/langley/Desktop/wordpress"def find_file_text(root_dir, target_text):    suffix = ['css', 'php', 'js', 'txt', 'html']<span style="white-space:pre"></span># 搜索文件的类型    for root, dirs, files in os.walk(root_dir):        for file in files:            file_suffix = file[file.find('.') + 1:len(file)]            if file_suffix in suffix:                file_obj = open(os.path.join(root, file), 'rU')                line_no = 0                for eachline in file_obj:                    line_no = line_no + 1                    if eachline.find(target_text) != -1:                        print "%s %d:%s" % (os.path.join(root, file), line_no, eachline)find_file_text(rootdir, 'fonts.google')



0 0