Ejercicio
Agregar Contenido A Un Archivo De Texto
Objectivo
Desarrollar un programa Python que solicite al usuario que ingrese varias oraciones y que se detenga cuando presione Enter sin escribir nada. El programa debe guardar estas oraciones en un archivo de texto llamado "sentences.txt". Si el archivo ya existe, el programa debe agregar la nueva entrada al final del contenido existente.
Ejemplo de ejercicio de Python
Mostrar código Python
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'.
Código de ejemplo copiado
Comparte este ejercicio de Python