Python How to Find a Word in a File

To find a word in a file using Python:

  1. Specify a target word.
  2. Open a file.
  3. Loop through the file line by line.
  4. Check if any line has the target word. If it does, print the line number and end the loop.

For example, let’s check where (if any) the word “test” is in a file called “example.txt”.

word = "test"

with open("example.txt", "r") as file:
    for line_number, line in enumerate(file, start=1):  
        if word in line:
          print(f"Word '{word}' found on line {line_number}")
          break

print("Search completed.")

In my case, the word is found in the second line. So the output is:

Word 'test' found on line 2
Search completed.

(The enumerate(file, start=1) matches each line with an index. Line 1 has an index of 1, line 2 has an index of 2, and so on. This simplifies the loop. Check out this article to learn more about enumerating in Python.)

How to Find the Longest Word in a File Using Python

To find the longest word(s) in a file:

  1. Open a file.
  2. Store the words in memory.
  3. Find the longest word.
  4. Find other possible words that are equally long.

For example, let’s find out the longest words in a file called “example.txt”:

with open("example.txt", "r") as file:
    words = file.read().split()

longest_word = max(words, key=len)
longest_words = [word for word in words if len(word) == len(longest_word)]

print(longest_words)

If you are confused, the max() function:

  • Loops through the words
  • Applies len function on each word.
  • Returns the word with the greatest value returned by the len. In other words, the longest word.

Also, learn more about list comprehensions to create shorthand for loops like the one in the last line.

How to Find and Replace a Word in a File Using Python

To find and replace a word in a file with Python:

  1. Open a file.
  2. Read the file in memory.
  3. Find and replace specific words.
  4. Write the fixed-up data back to the file.

Here is an example:

# Read the file in memory
with open("example.txt", "r") as file:
  data = file.read()

# Replace matches
data = data.replace("test", "banana")

# Write the data back to the file
with open("example.txt", "w") as file:
  file.write(data)

Thanks for reading. Happy coding!

Further Reading