gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
write a code in python to loop through a text
- User
write a code in python to loop through a text
- Assistant
Certainly! Below is a simple example of how you can loop through each line in a text file using Python. This code reads the contents of a text file and prints each line.
# Specify the path to your text file file_path = 'example.txt' # Open the file and read line by line with open(file_path, 'r') as file: for line in file: # Print each line, stripping leading/trailing whitespace print(line.strip())Explanation:
- Open the File: The
with open(file_path, 'r') as file:statement opens the file in read mode. It ensures that the file is properly closed after we're done. - Loop Through Lines: The
for line in file:loop iterates through each line in the file. - Print the Line: The statement outputs each line without leading or trailing whitespace.
- Open the File: The