查看目录/etc/nginx/nginx.conf 文件中是否包含 nns.baidu.com
要求: 过滤注释行,空行
import os
path = r'/etc/nginx/nginx.conf'
text = r'nns.baidu.com'
def getfiles(path):
f = open(path, "r")
# 在文件中找到要查到的字符串后进行打印
if text in f.read():
print(text + " found in ")
else:
print(text + " not found! ")
getfiles(path)
用正则表达式
def run():
symbol = "#" # 单行注释符号
start_multi_line_symbol = "'''" # 多行注释开始符号
end_multi_line_symbol = "'''" # 多行注释结束符号
string = "nns.baidu.com" # 判断字符串
file_path = "./con.conf" # 文件路径
is_exist = False
multi_line = False
with open(file_path, 'r') as f:
data = f.readlines()
for index, i in enumerate(data):
not_space = i.strip()
if not_space.startswith(start_multi_line_symbol) and not multi_line:
multi_line = True
continue
if not_space.endswith(end_multi_line_symbol):
multi_line = False
continue
if not not_space or not_space[0] == symbol or multi_line:
continue
line_data = i.split(symbol, 1)[0]
if string in line_data:
is_exist = True
print(f"行号:{index + 1}, {i}")
return is_exist
pass