python提取包含特定字符串的行_Python-在文件中搜索字符串并获取目标字符串所在的行号...

2020年1月15日

|

by YoungTimes

|

No comments

Python-在文件中搜索字符串并获取目标字符串所在的行号

1、检查文件中是否包含目标字符串

为了检测文件中是否包含目标字符串,我们定义了check_if_string_in_file()函数,该函数的参数为:目标文件名和目标字符串。在函数中迭代获取文件的每一行,然后检测该行是否包含目标字符串,如果包含目标字符串,函数返回True;如果文件中所有行都不包含目标字符串,则返回False。

def check_if_string_in_file(file_name, string_to_search):

""" Check if any line in the file contains given string """

# Open the file in read only mode

with open(file_name, 'r') as read_obj:

# Read all lines in the file one by one

for line in read_obj:

# For each line, check if line contains the string

if string_to_search in line:

return True

return False

假设存在文本文件”sample.txt”,文件内容为:

Hello this is a sample file

It contains sample text

Dummy Line A

Dummy Line B

Dummy Line

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值