Python print all lines in file

How to Print Lines Containing Given String in File using Python?

In this article, we will show you how to print all the lines that contain a given specific string in a given text file using python.

Assume we have taken a text file with the name ExampleTextFile.txt consisting of some random text. We will return the lines from a text file containing a given particular string from a text file.

Good morning to TutorialsPoint This is TutorialsPoint sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome to TutorialsPoint Learn with a joy Good morning to TutorialsPoint

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the path of the text file.
  • Enter the string as static/dynamic input and store it in a variable.
  • Use the open() function (opens a file and returns a file object as a result) to open the text file in read-only mode by passing the file name, and mode as arguments to it (Here “r” represents read-only mode).
with open(inputFile, 'r') as filedata:
  • Traverse in each line of the text file using the for loop
  • Using the if conditional statement and “in” keyword, check whether the given string is present in the above line data.
Читайте также:  Github action python install

The in keyword is used to determine whether a value exists in a sequence (list, range, string etc).

It is also used to iterate through a sequence in a for loop

  • Print the line, if the given string is found in that corresponding line.
  • Close the input file with the close() function (used to close an opened file).

Example

The following program checks line by line if the given string is found in a line from a text file and prints the line if the string is found −

# input text file inputFile = "ExampleTextFile.txt" # Enter the string givenString = "to TutorialsPoint" print('The following lines contain the string , givenString, '>:') # Opening the given file in read-only mode with open(inputFile, 'r') as filedata: # Traverse in each line of the file for line in filedata: # Checking whether the given string is found in the line data if givenString in line: # Print the line, if the given string is found in the current line print(line) # Closing the input file filedata.close()

Output

On executing, the above program will generate the following output −

The following lines contain the string < to TutorialsPoint >: Good morning to TutorialsPoint Welcome to TutorialsPoint Good morning to TutorialsPoint

We read a text file containing some random text in this program. We read the text file line by line, then checking to see if the given string appeared in that line data. If it is present, then we printed the line’s current value (Total Line Value).

Conclusion

We learned how to read the file, traverse the file line by line, and get all the line data this article. Once we get them, we may reverse the line, change the case, find number of words in that line, check the vowels, retrieve line characters, and so on. We also learned how to search for a string in a file and print the relevant line, which is mostly used in typical daily applications like looking for an id and printing all of the person’s information.

Источник

Python Program to Print Lines Containing Given String in File

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.

Things to do Before 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:

python print line containing string in 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()

print lines containing string in file python

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):

list lines containing string in file python

Modified Version of Previous Program

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:

print all lines containing given string in file python

Here is another sample run with user input, codescracker.txt as file name, and what as string:

print lines containing given string in file python

And here is the last sample run of this program, with user input temp.txt (a non existing file) as file name:

python print all lines containing string in file

As you can see with the above (last sample run), the exception handling code gets the exception and prints the error message.

Liked this article? Share it!

Источник

Оцените статью