๐Ÿ
B.TECH I YEAR โ€ข II SEMESTER โ€ข R25

Python Programming - Lab Manual

Python Programming Laboratory โ€ข Program Solution

๐Ÿ“˜ R25 Regulation ๐ŸŽ“ I Year ๐Ÿ“š II Semester ๐Ÿ Python Programming ๐Ÿงช Lab Program
Selected Program

check for given words

โ† All Python Programs

Aim:

☛   Write a Python code to open a given file and construct a function to check for given words present in it and display on found.

Solution :


PROGRAM: (check_words.py)

 
def search_str(file_path):
	search_word = input(" Enter a word you want to search in file : ")
	with open(file_path , 'r') as file :
		# read all content of a file
		content = file.readlines()
		# check if string present in a file
		for word in content :
			if word.find(search_word) != -1:
				print('The search word exists in the file & available at line = ' ,content.index(word))
				break
			else :
				print(" string does not exist in a file ")
	file.close()

file = open("search.txt",'w')
Lines = ["Hai \n ","This is Python Programming \n ","Welcome to study glance \n "]
file.writelines(Lines)
file.close()
search_str('search.txt')

OUTPUT:

 
Enter a word you want to search in file : to
string does not exist in a file
string does not exist in a file
The search word exists in the file & available at line =  2

image

๐Ÿ’ป Run This Python Program

check for given words
The selected Python program is loaded automatically into the editor. Edit the program, provide input if required and click Run.

The compiler is embedded using OneCompiler. Your Python program runs inside the embedded Python environment; Study Glance does not execute Python code directly on your web server.
โ† Back to Python Lab Programs ๐Ÿ“š All Lab Manuals