环境:centos7.6
python版本:python3.7
需求:需要判断一个字符串是否存在于某个文件中,类似于linux中grep命令。
import os
# 判断字符串str1是否存在于nginx.conf文件中
# 思路:将文件一行一行读出,然后判断字符串是否在这一行里面,如果是就打印“bingo”
str1 = 'worker_connections'
print(os.getcwd())
with open('nginx.conf', 'r') as f:
for line in f.readlines():
if str1 in line:
print('bingo')