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!
read_file.read()reads and return the whole content of the file but you are doing nothing with it. 2. You assignedword = "ape", but I don't see an use for it. You are not using this value and it's going to be replaced by theforin the next line if there's anydata. 3.data.split()return a list of words separated by spaces (doesn't work in place), but you are doing nothing with it.