我有一套压缩的TSV。广州tsv格式和一些未压缩的文件,如目录中的*.tsv。在
我想从这些文件中获取一个字符串,并在一个新行中打印grep结果。在
我有一个函数,它在输入目录中输入tsv和*。广州tsv存储和要搜索的字符串。在
import sys, os, traceback,subprocess,gzip,glob
def filter_from_tsvs(input_dir,string):
tsvs = glob.glob(os.path.join(input_dir,'*.tsv*'))
open_cmd=open
for tsvfile in tsvs:
print os.path.splitext
extension = os.path.splitext(tsvfile)[1]
if extension == ".gz":
open_cmd = gzip.open
print open_cmd
try:
print subprocess.check_output('grep string tsvfile', shell=True)
except Exception as e:
print "%s" %e
print "%s" %traceback.format_exc()
return
我还尝试使用:
^{pr2}$我得到这个错误:
gzip: tsvfile.gz: No such file or directory
Command 'zgrep pbuf tsvfile' returned non-zero exit status 2
Traceback (most recent call last):
File "ex.py", line 23, in filter_from_maintsvs
print subprocess.check_output('zgrep pbuf tsvfile', shell=True)
File "/datateam/tools/opt/lib/python2.7/subprocess.py", line 544, in check_output
raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command 'zgrep pbuf tsvfile' returned non-zero exit status 2
如何在python中使用grep/zgrep?
提前谢谢你的帮助。在
对代码的一些注释:
现在,您已经将要查找的字符串和文件名硬编码为“string”和“tsvfile”。试试这个:
接下来,如果使用
^{pr2}$zgrep
,则不需要使用gzip.open
打开文件。您可以对tsv.gz
文件调用zgrep,它将负责打开它,而不需要您做任何额外的工作。所以试着打电话请注意,
zgrep
也可以处理未压缩的tsv
文件,因此不需要在grep和zgrep之间切换。在在经历了blog之后,我得到了以下解决方案:)
提示:
grep
以退出代码1结尾,check\u输出将引发异常。在相关问题 更多 >
编程相关推荐