This article is created to cover some programs in Python that find and prints lines containing any given string (entered by user at run-time) in a given file (also entered by user at run-time). Let's do some task before proceeding the program.
Because the program given below is used to list and print all lines that contains the string entered by user in a text file. Therefore a text file say codescracker.txt must be created and saved inside the current directory. So create a file with following content:
Hello Python I'm a File My name is codescracker.txt The name of website is codescracker.com
Save this file with name codescracker.txt in the folder where the python program to print lines containing given string in a text file is saved. Here is the snapshot that shows the content of newly created file:
The question is, write a Python program to print lines that contains the string entered by user. The program given below is answer to this question:
print("Enter the Name of File: ") fileName = input() print("Enter the String: ") text = input() fileHandle = open(fileName, "r") lines = fileHandle.readlines() for line in lines: if text in line: print(line) fileHandle.close()
Here is its sample run:
Now supply inputs say codescracker.txt as name of file, then codescracker as string to print all the lines that contains codescracker, the given string, in given file (codescracker.txt):
This program uses try-except, an exception handling code to handle the exception such as file doesn't exist, the directory is not accessible etc. like things. Let's have a look at the program and its sample run for clear understanding.
print(end="Enter File's Name: ") fileName = input() try: fileHandle = open(fileName, "r") print(end="Enter the String: ") text = input() lines = fileHandle.readlines() lineList =  i = 0 for line in lines: if text in line: lineList.insert(i, line) i = i+1 fileHandle.close() if i==0: print("\n\"" +text+ "\" is not found in \"" +fileName+ "\"!") else: lineLen = len(lineList) print("\n---Lines containing \"" +text+ "\"---\n") for i in range(lineLen): print(end=lineList[i]) print() except IOError: print("\nThe file doesn't exist!")
Here is its sample run with exactly same user input as of previous program's sample run:
Here is another sample run with user input, codescracker.txt as file name, and what as string:
And here is the last sample run of this program, with user input temp.txt (a non existing file) as file name:
As you can see with the above (last sample run), the exception handling code gets the exception and prints the error message.
© Copyright 2021. All Rights Reserved.