私はプログラミングが初めてで、Python スクリプトをいじっています。
テキストファイルを読み取って画面に出力し、単語を検索し、単語が見つかるたびにその行のデータを分割する Python スクリプトを作成しようとしています。
test.txt ファイルは次のようになります。
ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar
画面上の最終結果を次のようにしたい:
ape bear cat dog
ape elephant frog giraffe
ape horse iguana jaguar
これまでの私のコード:
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)
スクリプトで何度も使用するつもりなので、ファイルを変数にしました。
コードをテストしたところ、for ループは 1 回のループで停止しませんでした。最終的には終了しましたが、コードまたはプログラムが自動的に無限ループを終了したのは確かです。
ファイルの最後に到達すると for ループが停止するようにコードを編集するにはどうすればよいですか? そして、このコードを書くためのより正しい方法はありますか?
繰り返しますが、これは単なるサンプル ファイルであり、実際のファイルではありません。ありがとう!