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