Exercise
Adding Content To A Text File
Objective
Develop a Python program that prompts the user to input multiple sentences, stopping when they press Enter without typing anything. The program should save these sentences in a text file called "sentences.txt." If the file already exists, the program must append the new input to the end of the existing content.
Example Python Exercise
Show Python Code
def collect_and_save_sentences():
"""
Collects multiple sentences from the user and saves them to a file.
If the file already exists, appends the new sentences to the end.
Stops when the user presses Enter without typing anything.
"""
sentences = []
print("Enter sentences. Press Enter without typing anything to finish.")
while True:
sentence = input("Enter a sentence: ")
# If the user presses Enter without typing anything, stop collecting sentences
if not sentence:
break
# Add the sentence to the list
sentences.append(sentence)
# Append the sentences to 'sentences.txt', creating the file if it doesn't exist
with open("sentences.txt", "a") as file:
for sentence in sentences:
file.write(sentence + "\n")
print(f"\n{len(sentences)} sentences were added to 'sentences.txt'.")
if __name__ == "__main__":
collect_and_save_sentences()
Output
Enter sentences. Press Enter without typing anything to finish.
Enter a sentence: First sentence.
Enter a sentence: Another sentence.
Enter a sentence:
2 sentences were added to 'sentences.txt'.
Share this Python Exercise