Cómo añadir texto a un archivo en Python

Jinku Hu 30 enero 2023
  1. file.write para añadir texto a un archivo con modo a
  2. Añade el parámetro opcional file a la función print en Python 3
  3. Añadir una nueva línea al añadir texto a un archivo
Cómo añadir texto a un archivo en Python

Este artículo del tutorial introducirá cómo añadir texto a un archivo en Python.

file.write para añadir texto a un archivo con modo a

Puede abrir el archivo en modo a o a+ si quiere añadir texto a un archivo.

destFile = r"temp.txt"
with open(destFile, "a") as f:
    f.write("some appended text")

El código anterior añade el texto some appended text junto al último carácter del archivo. Por ejemplo, si el archivo termina con this is the last sentence, entonces se convierte en this is the last sentencesome appended text después de añadirlo.

Creará el fichero si el fichero no existe en la ruta dada.

Añade el parámetro opcional file a la función print en Python 3

En Python 3, puedes print el texto en el archivo con el parámetro opcional file habilitado.

destFile = r"temp.txt"
Result = "test"
with open(destFile, "a") as f:
    print("The result will be {}".format(Result), file=f)

Añadir una nueva línea al añadir texto a un archivo

Si prefiere añadir el texto en la nueva línea, necesita añadir el salto de línea \r\n después del texto añadido para garantizar que el siguiente texto añadido se añada en la nueva línea.

destFile = r"temp.txt"
with open(destFile, "a") as f:
    f.write("the first appended text\r\n")
    f.write("the second appended text\r\n")
    f.write("the third appended text\r\n")
Autor: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Artículo relacionado - Python File