hjames hjames - 6 months ago 12
Python Question

How to end for loop in Python?

I'm new to programming and am playing around with Python scripting.

I'm trying to write a Python script that will read a text file and print to screen, search for a word, and every time it finds the word, to split the data of that line.

The test.txt file looks something like:

ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar


I want the end result on screen to look like:

ape bear cat dog
ape elephant frog giraffe
ape horse iguana jaguar


My code so far:

file = "test.txt"
read_file = open(file, "r")
with read_file as data:
read_file.read()
print(data)
word = "ape"
for word in data:
data.split()
print(data)


I made the file a variable because I intend to use it many different times in the script.

When I tested the code, the for loop didn't stop after one loop. It eventually ended, but I'm sure if it was the code or program automatically ends infinite loops.

How do I edit the code so that the for loop will stop once it reaches the end of the file?
And is there a more correct way to write this code?

Again, this is just an example file, not my actual file.
Thanks!

Answer
fileName = "test.txt"
read_file = open(fileName, "r")
with read_file as open_file:
    data = open_file.read().rstrip()
    keyword = "ape"
    data = ' '.join(["\n"*(word == keyword) + word for word in data.split()]).strip()
#   data = data.replace(keyword, "\n"+keyword).strip()
    print(data)

OUTPUT:

# ape bear cat dog 
# ape elephant frog giraffe 
# ape horse iguana jaguar
Comments