Is this review this code for add a string to a txt file: salva las llamadas with…
- User
Is this review this code for add a string to a txt file:
salva las llamadas
with open("llamadas.txt", "r") as f: contenido = f.read() # Leer el contenido del archivo contenido_con_saltos = contenido + "\n\n" + msj + "\n" + "respuestas: "+ str(respuestas[0])+" "+str(respuestas[1])+" "+str(respuestas[2])+" "+str(respuestas[3]) # Agregar dos saltos de línea contenido_str = str(contenido_con_saltos) # Convertir a string with open("llamadas.txt", "w", encoding="utf-8") as f: f.write(contenido_str) # Escribir el contenido en el archivo modificado - Assistant
There are a few improvements I would recommend for this code:
- Change the file opening mode to 'a' (append) when writing to the file. This way you can directly add new content to the file without having to read the entire content first.
with open("llamadas.txt", "a", encoding="utf-8") as f: f.write("\n\n") # Add two newline characters before writing the message- Use a single
withstatement when appending to the file.
msj = "example message" # Replace this with your actual message respuestas = [1, 2, 3, 4] # Replace this with your actual responses with open("llamadas.txt", "a", encoding="utf-8") as f: f.write("\n\n") # Add two newline characters before writing the message f.write(msj) # Write the message f.write("\n") # Add a newline character before writing the responses for r in respuestas: f.write("respuesta: " + str(r) + " ") # Write the responses - User
Podrías realizar un código de python para guardar los mensajes en na carpeta "mensajes", por ejemplo: mensaje1.txt, cuando se genere otro mensaje lo guarda en mensaje2.txt y así sucesivamente
- Assistant
Claro, aquí te muestro un enfoque para lograr eso utilizando la función
pathlib.Pathy verificando si el archivo ya existe antes de crear el nuevo archivo de mensaje:import os from pathlib import Path folder = "mensajes" if not os.path.exists(folder): os.makedirs(folder) def guardar_mensaje(mensaje): numero_mensaje = 1 while True: # Generar el nombre del archivo nombre_archivo = f"mensaje{numero_mensaje}.txt" ruta_archivo = os.path.join(folder, nombre_archivo) # Revisar si el archivo ya existe if not Path(ruta_archivo).is_file(): break numero_mensaje += 1 with open(ruta_archivo, "a", encoding="utf-8") as f: f.write(mensaje) print(f"Mensaje guardado en: {ruta_archivo}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.