有一个文件 (query.txt),其中包含一些关键字/短语,需要使用 grep 与其他文件进行匹配。以下代码的最后三行工作正常,但是当在 while 循环内使用相同的命令时,它会进入无限循环或其他东西(即不响应)。
import os
f=open('query.txt','r')
b=f.readline()
while b:
cmd='grep %s my2.txt'%b #my2 is the file in which we are looking for b
os.system(cmd)
b=f.readline()
f.close()
a='He is'
cmd='grep %s my2.txt'%a
os.system(cmd)
首先,您没有正确迭代该文件。你可以简单地使用for b in f:
没有.readline()
stuff.
然后,一旦文件名包含任何在 shell 中具有特殊含义的字符,您的代码就会在您面前爆炸。使用subprocess.call http://docs.python.org/library/subprocess.html#subprocess.call代替os.system()
并传递一个参数列表。
这是一个固定版本:
import os
import subprocess
with open('query.txt', 'r') as f:
for line in f:
line = line.rstrip() # remove trailing whitespace such as '\n'
subprocess.call(['/bin/grep', line, 'my2.txt'])
但是,您可以通过不调用来进一步改进代码grep
根本不。
读my2.txt
改为字符串,然后使用re
模块来执行搜索。如果您根本不需要正则表达式,您甚至可以简单地使用if line in my2_content
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)