Python 检查文件txt中是否存在特定字符串
我试图检查文件文本中是否有特定字符串 因此,我有一个包含以下内容的文件:Python 检查文件txt中是否存在特定字符串,python,Python,我试图检查文件文本中是否有特定字符串 因此,我有一个包含以下内容的文件: Active Internet connections Proto Recv-Q Send-Q Local Address Foreign Address (state) rxbytes txbytes tcp4 0 0 192.168.1.6.50860 72.21.91.29.http CLOSE_WAIT
Active Internet connections
Proto Recv-Q Send-Q Local Address Foreign Address (state) rxbytes txbytes
tcp4 0 0 192.168.1.6.50860 72.21.91.29.http CLOSE_WAIT 892 691
tcp4 0 0 192.168.1.6.50858 www.v.dropbox.co.https ESTABLISHED 27671 7563
tcp4 0 0 192.168.1.6.50857 162.125.17.1.https ESTABLISHED 17581 3642
这是我的代码:
char = ""
file = open("location")
for i, line in enumerate(file):
addi = i + 1
if line.strip() == char:
print "MATCH FOUND on line " + str(addi)
print "finished"
为了实现这一点,我必须将整行粘贴到我的char var中。例如,如果我粘贴活动的Internet连接,它就可以工作,但是如果我放置Internet,它将直接进入打印完成的行。如何解决这个问题?在Python中,字符串只不过是字符列表。要检查另一个字符串中是否存在字符串,可以使用in运算符
if char in line:
# do something
您需要在中查找contains,而不是equals==。您还可以使用列表理解获取所有匹配项,然后打印结果:
char = "<search-string>"
with open("location") as file:
results = [i for i, line in enumerate(file, 1) if char in line]
if results:
print "MATCHES FOUND on lines " + ', '.join(results)
print "finished"
如果您需要更复杂的搜索规则,那么您可能希望查看regex模块,就像行中的char一样简单
示例用法是hit中的hi将为True,而hello中的hi将为False。可能希望尝试使用with open as来正确处理文件
使用in关键字比==更有效,因为如果它包含字符串,则需要匹配
此外,使用str.format比stuff+strvalue更具可读性
您正在检查该行是否在字符中,但应执行相反的操作,因为整行不在字符中:
另外,我建议不要使用char作为变量名。尝试使用更明确、不太含糊的名称,如pattern_to_find在Python中查找子字符串是一项非常简单的任务。Python的find和count方法在这种情况下非常有用
# This is the string you're looking for
ip = "192.168.1.6.50860"
# You need to do both, open and read file, to get its content
file = open("/home/my/own/directory/here/file.txt").read()
def findLine(text, string):
if string in text:
return "MATCH FOUND on line {}".format(text[0, text.find(string)].count("\n") + 1)
else:
return "MATCH NOT FOUND"
print(findLine(file, ip)) # Prints 3 (1-based indexing)
试试这个:
search = "what you want to find goes here"
filename = "file to read"
with open(filename) as f:
for i, line in enumerate(f, 1):
if search in line:
print "MATCH FOUND in line", i
您正在使用==进行完全匹配,而不是在中使用,例如,在line.strip:中使用if char,这将返回包含字符串char的所有行。您可以在空格上拆分该行,然后使用==来比较单词。例如,我怀疑您是否想检查文件中是否有net con或gn Addr。您必须进一步指定您的目标,比如您是否要搜索整个单词,或者部分匹配仍然很好,比如STAB in
# This is the string you're looking for
ip = "192.168.1.6.50860"
# You need to do both, open and read file, to get its content
file = open("/home/my/own/directory/here/file.txt").read()
def findLine(text, string):
if string in text:
return "MATCH FOUND on line {}".format(text[0, text.find(string)].count("\n") + 1)
else:
return "MATCH NOT FOUND"
print(findLine(file, ip)) # Prints 3 (1-based indexing)
search = "what you want to find goes here"
filename = "file to read"
with open(filename) as f:
for i, line in enumerate(f, 1):
if search in line:
print "MATCH FOUND in line", i