7/20/2023 0 Comments Python search for fileNext, using the story from the previous example, we’ll demonstrate how to count the number of times a word appears in a text file. Output True Count the Number of Occurrences of a String in a Text File Julia felt her heart leap into her throat.Įxample: Using the read() method to search a text file story_file = open("magic_story.txt",'r') She heard the clock tickingĪnd realized the magician had changed his shape since the last Using the read() method, we’ll search the following text file for the word “magician.” If the word we’re looking for is in the text file, the program will let us know by printing “True” to the console.Ī nervous laugh escaped her lips. This method returns a string containing a file’s contents. Search for a String in a Text File Using the read() MethodĪnother method we can use to read data from a text file in Python is read(). Output The magician appeared without a sound. With open("text_file.txt",'r') as text_file: # safely open the text file we created and search for a string Text_file.write("The magician appeared without a sound.") With the list of lines in hand, we can use a for loop to iterate through the text file and search for any lines containing the string “magician.” If one is found, the entire line is printed to the terminal.Įxample: Find a string in a text file with readlines() # create a new text file and write some text Then we’ll assign that data to a variable called lines. We’ll use the readlines() method to read the file’s data. In our first example, we’ll create a new text file and search it for a specific string.
0 Comments
Leave a Reply. |