Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中集成grep_Python_Python 2.7_Grep_Gzip - Fatal编程技术网

在Python中集成grep

在Python中集成grep,python,python-2.7,grep,gzip,Python,Python 2.7,Grep,Gzip,我正在学习Python,我的目标是打开gzip文件,输入搜索查询,然后打印出来,最后将结果输出到文件中 import gzip file = raw_input('Input Filepath: ') # input file path with gzip.open(file, 'rb') as f: # opens gzip fil .gz file_content = f.read() # reads the contents grep = raw_input('Ent

我正在学习Python,我的目标是打开
gzip文件
,输入搜索查询,然后打印出来,最后将结果输出到文件中

import gzip
file = raw_input('Input Filepath: ')  # input file path
with gzip.open(file, 'rb') as f:  # opens gzip fil .gz
    file_content = f.read()  # reads the contents
    grep = raw_input('Enter Search: ')  # grep asks for output
print(file_content)  # prints it in console

我还尝试了
print(file\u content,grep)
,但它只返回第一个查找。

grep实用程序将搜索与给定模式匹配的行

要在python中执行此操作,需要逐行读取文件,然后在每行中搜索要查找的字符串:

import gzip

matched_lines = []
file = raw_input('Imput Filepath: ')
with gzip.open( file, 'rb') as f:
    grep = raw_input('Enter Search: ')
    for line in f: # read file line by line
        if grep in line: # search for string in each line
            matched_lines.append(line) # keep a list of matched lines

file_content = ''.join(matched_lines) # join the matched lines

print(file_content)

如果我没弄错你的问题,听起来你好像在做类似的事情

with gzip.open( file, 'rb') as f: #opens gzip fil .gz
    grep = raw_input('Enter Search: ')
    file_content = [line for line in f.readlines() if re.match(grep, line)]

请包括您的文件内容示例以及给定grep值的预期输出。不确定您在这里尝试做什么
grep
是一个命令行实用程序。你想在这里复制它的行为吗?@ettanany我想打开gz文件,然后只输出我在“搜索”中输入的信息,我想使用grep,因为这就是我知道/知道如何通过只做得到结果的最好方法。如果
文件内容
是一个字符串,那么你可以使用标准的字符串函数,比如
find()
。如果你需要像grep这样的东西,那么你需要正则表达式和模块
re
文件内容s3r324233e-2313314ss-Sf324sgthtj65u234:**:2016-12-05 18:54:48529信息[w.v.w.p.smallbigfirmInterceptor]。?http-bio-8090-exec-32--我的_标记:e2a61197-5bf3-4cdc-5555-8486f4c7ef61他们的_标记:sitetositerequest,所以我尝试打印出包含“sitetositerequest”的行,这按预期工作。它输出我需要的结果。我事先使用的代码有多糟糕?我读readlines()不好,因为它在内存中捕获信息。@JJWatt。是的,
readlines()
首先将所有行放入一个列表中,因此对于一个非常大的文件,它可能会占用大量内存。但是,有时您不得不这样做(例如,如果您想对所有行进行排序)。