gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Write Python program that reads first word from each line of given file and prints list…
- User
Write Python program that reads first word from each line of given file and prints list of this words separated by " , ".
- Assistant
Certainly! Below is a Python program that reads the first word from each line of a given file and prints a list of those words, separated by a comma and a space.
def read_first_words(file_path): first_words = [] try: with open(file_path, 'r') as file: for line in file: # Split the line into words and take the first one words = line.split() if words: # Check if the line is not empty first_words.append(words[0]) # Join the list of words with ", " and print it print(", ".join(first_words)) except FileNotFoundError: print(f"The file '{file_path}' was not found.") except Exception as e: print(f"An error occurred: {e}") # Example usage: Replace 'example.txt' with the path to your file read_first_words('example.txt')Instructions to Use:
- Save the program above to a file, e.g.,
read_first_words.py. - Replace
'example.txt'in the function call with the path to your input file.
- Save the program above to a file, e.g.,