Skip to main content
 首页 » 编程设计

Python:在文件中查找字符串

2025年05月04日28shangdawei

我的 python 脚本中有以下内容..

hostIP = sys.argv[1] 
hostsFileLoc = "hosts.txt" 
 
if not hostIP in open(hostsFileLoc).read(): 
    # Script to add if the string is not in file 
else: 
    # Print message 

唯一的问题是它不是精确匹配,例如...

如果我的文件包含:

192.168.0.111 

我的主机IP是:

192.168.0.11 

然后它将找到匹配项。我想我可以用正则表达式来做到这一点,因为总会有一个空格 ("\s+") 或一个逗号 ("\,") 所以我我想我可以用类似的东西

test = re.compile("^" + hostIP + "[\s\,]*") 

并使用 test 作为我的搜索,但这显然行不通。我试图找到一些关于此的文档,但无济于事。有没有人建议我如何使用带有正则表达式的变量来进行更具体的搜索。

谢谢

MHibbin

请您参考如下方法:

您可以通过分隔符(例如空格)拆分您的文本文件,然后在列表中查找字符串:

if not hostIP in open(hostsFileLoc).read().split(): 
    # Script to add if the string is not in file 
else: 
    # Print message 

如果您使用的不是空格,请将分隔符放入 split()