2016-12-26 70 views
0

我想学习一点Python,我的目标是打开gzip file,输入搜索查询然后打印出来,最终将结果输出到文件中。在Python中集成grep

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_content, grep),但它只返回第一个查找。

+1

请包括您的文件内容的示例以及给定grep值的预期输出。 – ettanany

+0

不知道你在这里试图做什么。 'grep'是一个命令行工具。你想在这里复制它的行为吗? –

+0

@ettanany我想打开gz文件,然后输出我在“搜索”中输入的信息我想用grep,因为我知道/知道如何才能得到结果 – JJWatt

回答

0

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) 
+0

这按预期工作。它输出我需要的结果。事先使用我的代码有多糟糕?我读readlines()是不好的,因为它捕获内存中的信息。 – JJWatt

+0

@JJWatt。是的,'readlines()'首先将所有行放入列表中,因此对于非常大的文件,它可能会使用大量内存。但是,有时候你被迫以这种方式做事(例如,如果你想对所有行进行排序)。 – ekhumoro

0

如果我正确理解你的问题,这听起来像你试图做类似

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)]